#include "Common.h"
#include "Resource.h"
#include "ResourceManager.h"
#include "NGLog.h"
#include "ChannelManager.h"
#include "WSSocket.h"
#include "WSSocketManager.h"
#include "WorldPacket.h"
#include "String.h"
#include "StringConverter.h"
#include "Users.h"
#include "UserManager.h"
#include "Character.h"
#include "CharManager.h"
#include "Items.h"
#include "ItemManager.h"
#include "Towns.h"
#include "MissionModelManager.h"
#include "ItemModelManager.h"
#include "TownManager.h"
#include "GameGoodsManager.h"
#include "EffectModelManager.h"
#include "GameDefine.h"
#include LOG_MGR_PATH
#include LOGIC_MGR_PATH
#include XMLDATA_MGR_PATH
#include PROTOCOLS_MGR_PATH
#include "Message.h"
#include "Mails.h"
#include "MailManager.h"
#include "json/json.h"
#include <openssl/evp.h>
#include "NoticeManager.h"
#include "Database/DatabaseEnv.h"
#include "AIInterface.h"
#include "GameUserCommand.h"
#include "VipCardManager.h"
#include "CenterBankManager.h"
#include "CenterFriendManager.h"
#include "CenterClubManager.h"
#include "Tools.h"
// #include "GoldCoronal.h"
#include "showip.h"
#include "ServerManager.h"
#include "PubDataManager.h"
#include "StringScreen.h"

/**
 * base64解密
 */
#include <openssl/bio.h> 
#include <openssl/buffer.h>
#include <openssl/sha.h> 
#include <openssl/hmac.h> 
#include <openssl/err.h>
// 检查玩家是否在本服务器
#define CHECK_USER_SERVER(serial) {	std::list<ResourcePtr> objs;\
									sUserMgr.getDBObjects(&objs, 0, 1, "`uid` = %u", serial);\
									if (objs.empty())\
										return SCR_RETURN_ERROR;\
									ResourcePtr obj_user = objs.front();\
									if (obj_user.isNull())\
										return SCR_RETURN_ERROR;\
									if (obj_user->getUInt32Field("active_gz_id"))\
									{\
										uint32 serverid = sChannelMgr.getServerID();\
										if (obj_user->getUInt32Field("active_gz_id") != serverid)\
										{\
											return SCR_FORWARD_RETURN_SUCCEED;\
										}\
									}\
								}

//--------------------------------------------------------------------
String unbase64(String input) 
{
	size_t length = input.size();
	BIO *b64, *bmem; 
	char *buffer = (char *)malloc(length); 
	memset(buffer, 0, length); 

	b64 = BIO_new(BIO_f_base64()); 
	BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL);
	bmem = BIO_new_mem_buf((void*)input.c_str(), length); 
	bmem = BIO_push(b64, bmem); 

	BIO_read(bmem, buffer, length); 

	BIO_free_all(bmem);
	String str(buffer);
	free(buffer);
	return str; 
}
//--------------------------------------------------------------------
bool StringReplace(String & str,const String & src, const String & dest,String::size_type start_index = 0)
{
	String::size_type iter;
	size_t srclen = src.size();
	bool re = false;
	while((iter = str.find(src,start_index)) != String::npos)
	{
		str.replace(iter, srclen, dest);
		re = true;
	}
	
	return re;
}
//--------------------------------------------------------------------
String DecryptBase64(String srcStr)
{
	String outStr = unbase64(srcStr);
	StringReplace(outStr, " ", "+");
	return outStr;
}

using namespace AIScript;
//-----------------------------------------------------------------------
int  script_process_world_game_command_register_user(void * info)
{
	if(!info)
		return SCR_RETURN_ERROR;
	
	GatewayCommand * command = (GatewayCommand *)info;
	Log.Debug("script_process_world_game_command_register_user","command id[%u],command_type[%u],command_str[%s]",command->cmdid,command->command_type,(command->parameter).c_str());	
	String str = command->parameter;
	
	Resource * user = sUserMgr.newDumyUser();
	if(!user)
		return SCR_RETURN_ERROR;
		
	String user_name;
	std::vector<String> ret = StringUtil::split(str,"=:");
	uint8 times = ret.size() / 2;
	for(uint8 i=0; i<times; ++i)
	{
		user_name = sGLMgr.RvRpDBCharacter(ret[i*2 + 1], true);
		if(ret[i*2].compare("name"))
		{
			if(sUserMgr.getDBCount("name = '%s'", ServerDatabase.EscapeString(user_name).c_str()))
			{
				sUserMgr.freeDumyUser(user);
				return SCR_RETURN_ERROR;
			}
		}
		user->setStringField(ServerDatabase.EscapeString(ret[i*2]),ServerDatabase.EscapeString(user_name));
	}

	user->setUInt32Field("reg_time",time(0));
	user->setUInt32Field("points",0);
	user->setUInt32Field("max_points",0);
	user->SaveDB();
	
	UserPtr userPtr = sUserMgr.loadUserDatabase(user);
	sUserMgr.freeDumyUser(user);
	if(userPtr.isNull())
		return SCR_RETURN_ERROR;
	uint32 uid = userPtr->getUInt32Field("uid");
	uint32 reg_time = userPtr->getUInt32Field("reg_time");
	
	String result = "uid=" + StringConverter::toString(uid) + ":" + "reg_time=" + StringConverter::toString(reg_time);
	command->result = result;
	Log.Debug("script_process_world_game_command_register_user","==================result[%s]",result.c_str());
	return SCR_RETURN_SUCCEED;
}

//-----------------------------------------------------------------------
int  script_process_world_game_command_reuser(void * info)
{
	if(!info)
		return SCR_RETURN_ERROR;
	
	GatewayCommand * command = (GatewayCommand *)info;
	Log.Debug("script_process_world_game_command_reuser","command id[%u],command_type[%u],command_str[%s]",command->cmdid,command->command_type,(command->parameter).c_str());
	String str = command->parameter;
	
	uint32 serial = command->uid;
	UserPtr user = sUserMgr.getByHandle(serial);
	if(user.isNull())
	{
		user = sUserMgr.load(serial);
		if(user.isNull())
			return SCR_RETURN_ERROR;
	}
	
	ResourcePtr socket = user->m_Socket.getResourcePtr();
	if(!socket.isNull())
		sGLMgr.DisconnectUserSocket(socket);
	
	Json::Reader reader; 
	Json::Value json_object; 
	if (!reader.parse(command->parameter.c_str(), json_object))
		return SCR_RETURN_ERROR;
	if (json_object.isMember("passwd"))
		user->setStringField("passwd", ServerDatabase.EscapeString(unbase64(json_object["passwd"].asString())));
	if (json_object.isMember("passwd2"))
		user->setStringField("passwd2",ServerDatabase.EscapeString(unbase64(json_object["passwd2"].asString())));
	if (json_object.isMember("nick"))
		user->setStringField("nick",ServerDatabase.EscapeString(unbase64(json_object["nick"].asString())));
	if (json_object.isMember("email"))
		user->setStringField("email",ServerDatabase.EscapeString(unbase64(json_object["email"].asString())));
	if (json_object.isMember("group_id"))
		user->setUInt32Field("group_id",json_object["group_id"].asUInt());
	if (json_object.isMember("flag"))
		user->setUInt32Field("flag",json_object["flag"].asUInt());
	if (json_object.isMember("vip"))
		user->setUInt32Field("vip",json_object["vip"].asUInt());
	
	user->SaveDB();
	Log.Debug("script_process_world_game_command_reuser","command id[%u] excuted!", command->cmdid);
	return SCR_RETURN_SUCCEED;
}

//-----------------------------------------------------------------------
int  script_process_world_game_command_deluser(void * info)
{
	if(!info)
		return SCR_RETURN_ERROR;
	
	GatewayCommand * command = (GatewayCommand *)info;
	Log.Debug("script_process_world_game_command_deluser","command id[%u],command_type[%u],command_str[%s]",command->cmdid,command->command_type,(command->parameter).c_str());
	String str = command->parameter;
	
	uint32 serial = command->uid;
	UserPtr user = sUserMgr.getByHandle(serial);
	if(user.isNull())
	{
		user = sUserMgr.load(serial);
		if(user.isNull())
			return SCR_RETURN_ERROR;
	}

	ResourcePtr socket = user->m_Socket.getResourcePtr();
	if(!socket.isNull())
		sGLMgr.DisconnectUserSocket(socket);

	uint32 char_id = user->getUInt32Field("char_id");
	if(char_id)
	{
		CharPtr chr = sCharMgr.getByHandle(char_id);
		if(chr.isNull())
		{
			chr = sCharMgr.load(char_id);
			if(!chr.isNull())
			{
				chr->Destroy();
			}
		}
	}
	
	Log.Notice("script_process_world_game_command_deluser","user[%u] destroy sucessfully!",user->getHandle());
	user->Destroy();
	
	return SCR_RETURN_SUCCEED;
}

//-----------------------------------------------------------------------
int  script_process_world_game_command_userbuy(void * info)
{
	if(!info)
		return SCR_RETURN_ERROR;

	GatewayCommand * command = (GatewayCommand *)info;
	Log.Debug("script_process_world_game_command_userbuy","command id[%u],command_type[%u],command_str[%s]",command->cmdid,command->command_type,(command->parameter).c_str());
	String str = command->parameter;
	uint32 serial = command->uid;
	Log.Notice("script_process_world_game_command_userbuy","command user id[%u]",serial);
	
	CHECK_USER_SERVER(serial)
	
	UserPtr user = sUserMgr.getByHandle(serial);
	if(user.isNull())
	{
		user = sUserMgr.load(serial);
		if(user.isNull())
			return SCR_RETURN_ERROR;
	}
	
	Json::Reader reader; 
	Json::Value json_object; 
	if (!reader.parse(command->parameter.c_str(), json_object))
		return SCR_RETURN_ERROR;
	uint32 golds = json_object["golds"].asUInt();
	user->setUInt32Field("golds",user->getUInt32Field("golds") + golds);
	user->SaveDB();
	// 公告
	char buf[256];
	memset(buf, 0, sizeof(buf));
	sprintf(buf, sMsg.getMessage("buy_golds").c_str(), user->getStringField("nick").c_str(), golds);
	sNoticeMgr.AddMsgToQueue(buf, 1, 0, 10);
	// 通知玩家
	ResourcePtr socket = user->m_Socket.getResourcePtr();
	if (!socket.isNull())
	{
		uint8 socket_type = socket->getType();
		if(socket_type == ResourceTypeWorldSocket)
		{
			WSSocketPtr wsocket = socket;
			WorldPacket packet;
			// 更新元宝
			if (sProtocolsMgr.CreateGoldsUpdatePacket(&packet, user->getUInt32Field("golds")))
				wsocket->SendPacket(&packet);
			// 下发消息
			sprintf(buf, sMsg.getMessage("buygolds").c_str(), golds);
			if(sProtocolsMgr.CreateLocalMessagePacket(&packet, buf, sMsg.getType("buygolds")))
				wsocket->SendPacket(&packet);
		}
	}
	// 记录日志
	sLogDataMgr.UpdateGoldsFromGatewayLog(user, en_UNT_Add, golds);
	
	Log.Notice("script_process_world_game_command_userbuy","user[%u] buy golds[%u] sucessfully!",user->getHandle(),golds);
	
	return SCR_RETURN_SUCCEED;
}

//-----------------------------------------------------------------------
int  script_process_world_game_command_lockuser(void * info)
{
	if(!info)
		return SCR_RETURN_ERROR;

	GatewayCommand * command = (GatewayCommand *)info;
	Log.Debug("script_process_world_game_command_lockuser","command id[%u],command_type[%u],command_str[%s]",command->cmdid,command->command_type,(command->parameter).c_str());
	String str = command->parameter;

	uint32 serial = command->uid;
	CHECK_USER_SERVER(serial)
	UserPtr user = sUserMgr.getByHandle(serial);
	if(user.isNull())
	{
		user = sUserMgr.load(serial);
		if(user.isNull())
			return SCR_RETURN_ERROR;
	}

	ResourcePtr socket = user->m_Socket.getResourcePtr();
	if(!socket.isNull())
		sGLMgr.DisconnectUserSocket(socket);

	Json::Reader reader; 
	Json::Value json_object; 
	if (!reader.parse(command->parameter.c_str(), json_object))
		return SCR_RETURN_ERROR;
	uint32 ban_time = json_object["ban_time"].asUInt();
	user->setUInt32Field("ban_time",ban_time);
	user->SaveDB();
	Log.Notice("script_process_world_game_command_lockuser","lock user[%u] sucessfully ban_time[%u]",user->getHandle(),ban_time);
	
	return SCR_RETURN_SUCCEED;
}

//-----------------------------------------------------------------------
int  script_process_world_game_command_unlockuser(void * info)
{
	if(!info)
		return SCR_RETURN_ERROR;

	GatewayCommand * command = (GatewayCommand *)info;
	Log.Notice("script_process_world_game_command_unlockuser","command id[%u],command_type[%u],command_str[%s]",command->cmdid,command->command_type,(command->parameter).c_str());
	String str = command->parameter;
	
	uint32 serial = command->uid;
	CHECK_USER_SERVER(serial)
	UserPtr user = sUserMgr.getByHandle(serial);
	if(user.isNull())
	{
		user = sUserMgr.load(serial);
		if(user.isNull())
			return SCR_RETURN_ERROR;
	}
	
	uint32 ban_time = user->getUInt32Field("ban_time") ? 0 : time(0);
	user->setUInt32Field("ban_time", ban_time);
	user->SaveDB();
	
	Log.Notice("script_process_world_game_command_unlockuser","UnLock user[%u] sucessfully!",user->getHandle());
	
	return SCR_RETURN_SUCCEED;
}

//-----------------------------------------------------------------------
int  script_process_world_game_command_notice(void * info)
{
	if(!info)
		return SCR_RETURN_ERROR;
	
	GatewayCommand * command = (GatewayCommand *)info;
	Log.Notice("script_process_world_game_command_notice","command id[%u],command_type[%u],command_str[%s]",command->cmdid,command->command_type,(command->parameter).c_str());
	// 用户ID
	uint32 uid = command->uid;
	Json::Reader reader; 
	Json::Value json_object; 
	if (!reader.parse(command->parameter.c_str(), json_object))
		return SCR_RETURN_ERROR;
	// 消息内容
	String strMsg(unbase64(json_object["message"].asString()));
	// 分区ID
	uint32 gzId = json_object["gz_id"].asUInt();
	// 消息类型
	uint32 type = json_object["emstype"].asUInt();
	if (uid)
		sGLMgr.SendMsgToPlayer(uid, strMsg, type); // 给某个玩家发信息
	else
	{
		// 起始日期
		uint32 startDate = json_object["start"].asUInt();
		// 结束日期
		uint32 finishDate = json_object["finish"].asUInt();
		// 开始时间
		uint32 beginTime = json_object["begin"].asUInt();
		// 结束时间
		uint32 endTime = json_object["end"].asUInt();
		// 频率
		uint32 interval = json_object["interval"].asUInt();
		sNoticeMgr.AddMsgToQueue(strMsg, type, gzId, interval, startDate, finishDate, beginTime, endTime); // 公告
	}
	
	Log.Notice("script_process_world_game_command_notice","command id[%u] excuted!", command->cmdid);
	return SCR_FORWARD_RETURN_SUCCEED;
}

//-----------------------------------------------------------------------
int  script_process_world_game_command_additem(void * info)
{
	if(!info)
		return SCR_RETURN_ERROR;
	
	GatewayCommand * command = (GatewayCommand *)info;
	Log.Debug("script_process_world_game_command_additem","command id[%u],command_type[%u],command_str[%s]",command->cmdid,command->command_type,(command->parameter).c_str());
	
	uint32 user_id = command->uid;
	CHECK_USER_SERVER(user_id)
	UserPtr user = sUserMgr.getByHandle(user_id);
	if(user.isNull())
	{
		user = sUserMgr.load(user_id);
		if(user.isNull())
			return SCR_RETURN_ERROR;
	}
	uint32 char_id = user->getUInt32Field("char_id");
	CharPtr chr = sCharMgr.getByHandle(char_id);
	if(chr.isNull())
	{
		chr = sCharMgr.load(char_id);
		if(chr.isNull())
			return SCR_RETURN_ERROR;
	}
	
	try
	{
		Json::Reader reader; 
		Json::Value json_object; 
		if (!reader.parse(command->parameter.c_str(), json_object))
			return SCR_RETURN_ERROR;
		if (!json_object.isMember("script_id"))
			return SCR_RETURN_ERROR;
		uint32 modelId = json_object["script_id"].asUInt();
		if(0 == modelId)
			return SCR_RETURN_ERROR;
		// 数量
		uint32 num = json_object["num"].asUInt();
		// 存入数据库
		sGLMgr.addItemNum(chr, modelId, num);
		
		// 记录日志
		sLogDataMgr.UpdateItemsInfoLog(chr, en_ST_Gateway, modelId, en_UNT_Add, num);
		Log.Notice("script_process_world_game_command_additem","user[%u] additem scriptid[%u] num[%u] sucessfully!",user->getHandle(), modelId,num);
	}
	catch (exception& e) 
	{
		return SCR_RETURN_ERROR;
	}
	
	return SCR_RETURN_SUCCEED;
}

//-----------------------------------------------------------------------
int  script_process_world_game_command_deleteitem(void * info)
{
	if(!info)
		return SCR_RETURN_ERROR;
	
	GatewayCommand * command = (GatewayCommand *)info;
	Log.Debug("script_process_world_game_command_deleteitem","command id[%u],command_type[%u],command_str[%s]",command->cmdid,command->command_type,(command->parameter).c_str());
	
	uint32 user_id = command->uid;
	CHECK_USER_SERVER(user_id)
	UserPtr user = sUserMgr.getByHandle(user_id);
	if(user.isNull())
	{
		user = sUserMgr.load(user_id);
		if(user.isNull())
			return SCR_RETURN_ERROR;
	}
	uint32 char_id = user->getUInt32Field("char_id");
	CharPtr chr = sCharMgr.getByHandle(char_id);
	if(chr.isNull())
	{
		chr = sCharMgr.load(char_id);
		if(chr.isNull())
			return SCR_RETURN_ERROR;
	}
	Json::Reader reader; 
	Json::Value json_object; 
	if (!reader.parse(command->parameter.c_str(), json_object))
		return SCR_RETURN_ERROR;
	if (!json_object.isMember("script_id"))
		return SCR_RETURN_ERROR;
	uint32 modelId = json_object["script_id"].asUInt();
	if(0 == modelId)
		return SCR_RETURN_ERROR;
	// 数量
	uint32 num = json_object["num"].asUInt();
	// 存入数据库
	sGLMgr.reduceItemNum(chr, modelId, num);
	
	// 记录日志
	sLogDataMgr.UpdateItemsInfoLog(chr, en_ST_Gateway, modelId, en_UNT_Reduce, num);
	Log.Notice("script_process_world_game_command_deleteitem","user[%u] reduceitem scriptid[%u] num[%u] sucessfully!",user->getHandle(), modelId,num);
	
	return SCR_RETURN_SUCCEED;
}

int SERVER_DECL script_process_world_game_command_operationitem(void * info)
{
	if(!info)
		return SCR_RETURN_ERROR;
	
	GatewayCommand * command = (GatewayCommand *)info;
	Log.Debug("script_process_world_game_command_operationitem","command id[%u],command_type[%u],command_str[%s]",command->cmdid,command->command_type,(command->parameter).c_str());
	
	uint32 user_id = command->uid;
	CHECK_USER_SERVER(user_id)
	UserPtr user = sUserMgr.getByHandle(user_id);
	if(user.isNull())
	{
		user = sUserMgr.load(user_id);
		if(user.isNull())
			return SCR_RETURN_ERROR;
	}
	uint32 char_id = user->getUInt32Field("char_id");
	CharPtr pChr = sCharMgr.getByHandle(char_id);
	if(pChr.isNull())
	{
		pChr = sCharMgr.load(char_id);
		if(pChr.isNull())
			return SCR_RETURN_ERROR;
	}
	AICreatureBaseInterface *pAiChrInfe = TO_CREATURE_BASE_INTERFACE(pChr->getAIInterface());
	if (!pAiChrInfe)
		return SCR_RETURN_ERROR;
	Json::Reader reader; 
	Json::Value json_object; 
	if (!reader.parse(command->parameter.c_str(), json_object))
		return SCR_RETURN_ERROR;
	std::vector<std::string> vecKeys = json_object.getMemberNames();
	std::vector<std::string>::iterator iter = vecKeys.begin();
	String strContent;
	uint32 amount = 0;
	bool bOk = true;
	Json::Value root; // 返回信息
	Json::FastWriter fWriter; 
	for (; iter != vecKeys.end(); ++iter)
	{
		if (StringUtil::startsWith((*iter),"addi"))
		{
			uint32 op;
			std::vector<String> strInfo = StringUtil::split(unbase64(json_object[(*iter)].asString()),"|");
			// 操作				
			if(strInfo.size() < 3)
				return SCR_RETURN_ERROR;
			else if(strInfo.size() == 3)
			{
				op = 1;
			}
			else
			{
				op = StringConverter::parseUnsignedInt(strInfo[3]);
				if(op == 0)
					op = 1;
			}
			
			if(strInfo[0] == "" || strInfo[1] == "")
				return SCR_RETURN_ERROR;
			// 模式ID
			uint32 modelId = StringConverter::parseUnsignedInt(strInfo[0]);
			// 数量
			uint32 num = StringConverter::parseUnsignedInt(strInfo[1]);
			// 名称
			String szName = strInfo[2];
			
			uint8 re = 0;
			if(op == 1)
			{// 增加
				re = !sGLMgr.addItemNum(pChr, modelId, num).isNull();
			}
			else if(op == 2)
			{// 减少
				re = sGLMgr.reduceItemNum(pChr, modelId, num);
			}
			
			if (re > 0)
			{
				sLogDataMgr.UpdateItemsInfoLog(pChr, en_ST_Gateway, modelId, op == 1 ? en_UNT_Add : en_UNT_Reduce, num);
			}
			else
			{
				bOk = false;
			}
			uint32 residue = sGLMgr.GetItemNum(pChr, modelId);
		
			Json::Value child; // 返回信息
			child["script_id"] = Json::Value(modelId);	// 模式号
			child["num"] = Json::Value(num);			// 数量
			child["name"] = Json::Value(szName);		// 名称
			child["op"] = Json::Value(op);				// 操作
			child["re"]  	 = Json::Value(re);			// 结果
			child["balance"]  = Json::Value(residue);	// 余额
			
			root[(*iter)] = Json::Value(child);
		}
		else if (StringUtil::startsWith((*iter),"message"))
		{
			// 消息内容
			String strMsg(unbase64(json_object[*iter].asString()));
			// 发信息
			sGLMgr.SendMsgToPlayer(user_id, strMsg, 1);
		}
		else if (StringUtil::startsWith((*iter),"amount"))
		{
			amount = uint32(StringConverter::parseReal(unbase64(json_object[*iter].asString())) * 100.0f);
		}
	}
	
	command->result = ServerDatabase.EscapeString(fWriter.write(root));
	// 更新COMMAND
	GatewayDatabase.WaitExecute("update gw_command set `result` = '%s' where `cmdid` = %u", command->result.c_str(), command->cmdid);
	Log.Notice("script_process_world_game_command_operationitem","user[%u] operationitem %s!command->result[%s]",user->getHandle(), bOk?"sucessfully":"failed", command->result.c_str());
	
	return bOk ? SCR_RETURN_SUCCEED : SCR_RETURN_ERROR;
}

//-----------------------------------------------------------------------
int script_process_world_game_command_reloadscripts(void * info)
{
	if(!info)
		return SCR_RETURN_ERROR;
	
	GatewayCommand * command = (GatewayCommand *)info;
	Log.Debug("script_process_world_game_command_reloadscripts","command id[%u],command_type[%u],command_str[%s]",command->cmdid,command->command_type,(command->parameter).c_str());
	
	ScriptFile *pFile = sItemMgr.getScriptFile();
	pFile->Reload();
	Log.Notice("script_process_world_game_command_reloadscripts","reloadscripts  item sucessfully!");
	
	return SCR_FORWARD_RETURN_SUCCEED;
}

//-----------------------------------------------------------------------
int script_process_world_game_command_reloaditemmodel(void * info)
{
	if(!info)
		return SCR_RETURN_ERROR;
	
	GatewayCommand * command = (GatewayCommand *)info;
	Log.Debug("script_process_world_game_command_reloaditemmodel","command id[%u],command_type[%u],command_str[%s]",command->cmdid,command->command_type,(command->parameter).c_str());
	
	std::list<ResourcePtr> rlist;
	sItemModelMgr.getItemModelsList(&rlist, 0, 1000,"");
	std::list<ResourcePtr>::iterator ri, endri = rlist.end();
	for (ri = rlist.begin(); ri != endri; ++ ri)
	{		
		(*ri)->reload();
	}	
	
	Log.Notice("script_process_world_game_command_reloaditemmodel","reloadscripts  item sucessfully!");	
	return SCR_FORWARD_RETURN_SUCCEED;
}

//-----------------------------------------------------------------------
int script_process_world_game_command_reloadgoods(void * info)
{
	if(!info)
		return SCR_RETURN_ERROR;
	
	GatewayCommand * command = (GatewayCommand *)info;
	Log.Debug("script_process_world_game_command_reloadgoods","command id[%u],command_type[%u],command_str[%s]",command->cmdid,command->command_type,(command->parameter).c_str());
	
	sGoodsMgr.Reload();
	Log.Notice("script_process_world_game_command_reloadgoods","reloadscripts  item sucessfully!");
	
	return SCR_FORWARD_RETURN_SUCCEED;
}

//-----------------------------------------------------------------------
int script_process_world_game_command_reloadtown(void * info)
{
	if(!info)
		return SCR_RETURN_ERROR;
	
	GatewayCommand * command = (GatewayCommand *)info;
	Log.Debug("script_process_world_game_command_reloadtown","command id[%u],command_type[%u],command_str[%s]",command->cmdid,command->command_type,(command->parameter).c_str());

	std::list<ResourcePtr> towns;
	sTownMgr.getResourceList(&towns);
	std::list<ResourcePtr>::iterator ti, endti = towns.end();
	for(ti = towns.begin(); ti != endti; ti ++)
	{
		(*ti)->ReloadDB();
	}
	
	Log.Notice("script_process_world_game_command_reloadtown","reloadscripts  towns[%u] sucessfully!", towns.size());
	
	return SCR_FORWARD_RETURN_SUCCEED;
}

//-----------------------------------------------------------------------
int script_process_world_game_command_reloadmissionmodel(void * info)
{
	if(!info)
		return SCR_RETURN_ERROR;
	
	GatewayCommand * command = (GatewayCommand *)info;
	Log.Debug("script_process_world_game_command_reloadmissionmodel","command id[%u],command_type[%u],command_str[%s]",command->cmdid,command->command_type,(command->parameter).c_str());
	
	std::list<ResourcePtr> rlist;
	sMissionModelMgr.getMissionModelsList(&rlist, 0, 1000,"");
	std::list<ResourcePtr>::iterator ri, endri = rlist.end();
	for (ri = rlist.begin(); ri != endri; ++ ri)
	{		
		(*ri)->reload();
	}	
	Log.Notice("script_process_world_game_command_reloadmissionmodel","reloadscripts item sucessfully!");
	
	return SCR_FORWARD_RETURN_SUCCEED;
}

//-----------------------------------------------------------------------
int script_process_world_game_command_reloadeffectmodel(void * info)
{
	if(!info)
		return SCR_RETURN_ERROR;
	
	GatewayCommand * command = (GatewayCommand *)info;
	Log.Debug("script_process_world_game_command_reloadeffectmodel","command id[%u],command_type[%u],command_str[%s]",command->cmdid,command->command_type,(command->parameter).c_str());
	
	std::list<ResourcePtr> effects;
	sEffectModelMgr.getEffectModelsList(&effects, 0, 1000, "flag = %u", 1);
	std::list<ResourcePtr>::iterator ei, endei = effects.end();
	for(ei = effects.begin(); ei != endei; ++ ei)
	{
		(*ei)->reload();
	}
	Log.Notice("script_process_world_game_command_reloadeffectmodel","reloadscripts item sucessfully!");
	
	return SCR_FORWARD_RETURN_SUCCEED;
}
//-----------------------------------------------------------------------
int script_process_world_game_command_addmail(void * info)
{
	if(!info)
		return SCR_RETURN_ERROR;
	GatewayCommand * command = (GatewayCommand *)info;
	Log.Debug("script_process_world_game_command_addmail","command id[%u],command_type[%u],command_str[%s]",command->cmdid,command->command_type,(command->parameter).c_str());
	uint32 user_id = command->uid;
	CHECK_USER_SERVER(user_id)
	UserPtr user = sUserMgr.getByHandle(user_id);
	if(user.isNull())
	{
		user = sUserMgr.load(user_id);
		if(user.isNull())
			return SCR_RETURN_ERROR;
	}
	
	Json::Reader reader; 
	Json::FastWriter w;
	Json::Value json_object,json_mailCon;
	if (!reader.parse(command->parameter.c_str(), json_object))
		return SCR_RETURN_ERROR;

	GameMail *pMail = sChannelMgr.newDumyMail();
	if (NULL == pMail)
		return SCR_RETURN_ERROR;
	pMail->group_id = command->group_id; // 邮件组ID
	pMail->status = Mail::MailStatusRecv; // 邮件状态
	pMail->recv_serial = user->getUInt32Field("platform_id"); // 接收方用户ID
	pMail->title = ServerDatabase.EscapeString(DecryptBase64(json_object["title"].asString())); // 标题
	String strData = json_object["content"].asString();
	String outData = unbase64(strData);
	outData = ServerDatabase.EscapeString(outData);
	
	String::size_type start = outData.find("\n\n");
	StringReplace(outData, " ", "+",start);
	
	uint32 days = 7;
	if(json_object.isMember("days"))
		days = json_object["days"].asUInt();
	
	// 附件添加
	if(json_object.isMember("items"))
	{
		bool bHasItems = false;
		for (Json::Value::iterator iter=json_object["items"].begin(); iter!=json_object["items"].end(); ++iter)
		{
			bHasItems = true;
			json_mailCon["items"][iter.key().asString()] = StringConverter::parseUnsignedInt((*iter).asString());
		}
		
		if(bHasItems)
		{
			pMail->data1 = 1;
			pMail->data2 = en_ST_Gateway;
		}
	}
	
	if (json_object["flag"].asUInt() == 1)
	{
		pMail->flag = 0x80;
		json_mailCon["content"] = outData;
		pMail->contenct = w.write(json_mailCon); // 内容
	}
	else
	{
		json_mailCon["content"] = ServerDatabase.EscapeString(outData);
		pMail->contenct = w.write(json_mailCon); // 内容
	}
	
	pMail->create_time = time(0); 						// 创建时间
	pMail->expiration_time = time(0) + days * 86400; 	// 过期时间
	
	if(!sGLMgr.CheckExpireMails(pMail->recv_serial,command->gz_id))
	{
		Log.Error("script_process_world_game_command_addmail", "clean user[%d] mail box faild!", user_id);
		return SCR_RETURN_ERROR;
	}
	
	// 清理邮箱
	if (!sGLMgr.CleanUserMails(pMail->recv_serial))
	{
		Log.Error("script_process_world_game_command_addmail", "clean user[%d] mail box faild!", user_id);
		return SCR_RETURN_ERROR;
	}
	// 保存到数据库
	if ((sChannelMgr.addMailDB(pMail) == 0))
	{
		Log.Error("script_process_world_game_command_addmail", "save user[%d] mail box to DB faild!", user_id);
		return SCR_RETURN_ERROR;
	}
	
	sChannelMgr.freeDumyMail(pMail);
	// 添加成功，通知玩家
	WSSocketPtr socket = user->m_Socket.getResourcePtr();
	if (!socket.isNull())
	{
		WorldPacket packet;
		if (sProtocolsMgr.CreateSendUnreadMailNumberPacket(&packet, user))
			socket->SendPacket(&packet);
		// 下发消息通知玩家
		if(sProtocolsMgr.CreateLocalMessagePacket(&packet, sMsg.getMessage("newmail"), sMsg.getType("newmail")))
			socket->SendPacket(&packet);
	}
	Log.Notice("script_process_world_game_command_addmail","add user[%u]'s mail sucessfully!",user_id);
	
	return SCR_RETURN_SUCCEED;
}

//-----------------------------------------------------------------------
int script_process_world_game_command_refundment(void * info)
{
	if(!info)
		return SCR_RETURN_ERROR;
	
	GatewayCommand * command = (GatewayCommand *)info;
	Log.Debug("script_process_world_game_command_refundment","command id[%u],command_type[%u],command_str[%s]",command->cmdid,command->command_type,(command->parameter).c_str());
	
	uint32 user_id = command->uid;
	CHECK_USER_SERVER(user_id)
	UserPtr user = sUserMgr.getByHandle(user_id);
	if(user.isNull())
	{
		user = sUserMgr.load(user_id);
		if(user.isNull())
			return SCR_RETURN_ERROR;
	}
	uint32 char_id = user->getUInt32Field("char_id");
	CharPtr chr = sCharMgr.getByHandle(char_id);
	if(chr.isNull())
	{
		chr = sCharMgr.load(char_id);
		if(chr.isNull())
			return SCR_RETURN_ERROR;
	}
	Json::Reader reader; 
	Json::Value json_object; 
	if (!reader.parse(command->parameter.c_str(), json_object))
		return SCR_RETURN_ERROR;
	// String billId = unbase64(json_object["oid"].asString());
	// if(!billId)
		// return SCR_RETURN_ERROR;
	// uint32 goodsId = json_object["destmodelid"].asUInt();
	// uint32 gNum = json_object["destnum"].asUInt();
	uint32 itemModelId = json_object["srcmodelid"].asUInt();
	uint32 iNum = json_object["srcnum"].asUInt();
	// 存入数据库
	ItemPtr item = sGLMgr.addItemNum(chr, itemModelId, iNum);
	if(item.isNull())
		return SCR_RETURN_ERROR;
	// 记录日志
	sLogDataMgr.UpdateItemsInfoLog(chr, en_ST_Gateway, itemModelId, en_UNT_Add, iNum);
	Log.Notice("script_process_world_game_command_refundment","refundment user[%u] sucessfully!",user_id);
	
	return SCR_RETURN_SUCCEED;
}

int script_process_world_game_command_reloadgameconf(void * info)
{
	if(!info)
		return SCR_RETURN_ERROR;
	
	GatewayCommand * command = (GatewayCommand *)info;
	Log.Debug("script_process_world_game_command_reloadgameconf","command id[%u],command_type[%u],command_str[%s]",command->cmdid,command->command_type,(command->parameter).c_str());
	
	sXmlDataMgr.ReloadGameConfig();
	sXmlDataMgr.ReloadMailModel();
	Log.Notice("script_process_world_game_command_reloadgameconf","reloadgameconf item sucessfully!");
	
	return SCR_FORWARD_RETURN_SUCCEED;
}

int script_process_world_game_command_repwd2(void * info)
{
	if(!info)
		return SCR_RETURN_ERROR;
	
	GatewayCommand * command = (GatewayCommand *)info;
	Log.Debug("script_process_world_game_command_reloadgameconf","command id[%u],command_type[%u],command_str[%s]",command->cmdid,command->command_type,(command->parameter).c_str());
	
	uint32 user_id = command->uid;
	CHECK_USER_SERVER(user_id)
	UserPtr user = sUserMgr.getByHandle(user_id);
	if(user.isNull())
	{
		user = sUserMgr.load(user_id);
		if(user.isNull())
			return SCR_RETURN_ERROR;
	}	
	
	String pwd2 = DEFAULT_PASSWORLD;
	user->setStringField("passwd2", pwd2);
	user->SaveDB();
	// 重置银行密码
	sBankMgr.ResetPassworld(user);
	
	Log.Notice("script_process_world_game_command_repwd2","repwd2 user[%u]'s item sucessfully!",user_id);
	
	return SCR_RETURN_SUCCEED;
}

int SERVER_DECL script_process_world_game_command_addexchangecards(void * info)
{
	if(!info)
		return SCR_RETURN_ERROR;
	
	GatewayCommand * command = (GatewayCommand *)info;
	Log.Debug("script_process_world_game_command_addexchangecards","command id[%u],command_type[%u]",command->cmdid,command->command_type);
	
	Json::Reader reader; 
	Json::Value json_object; 
	if (!reader.parse(command->parameter.c_str(), json_object))
		return SCR_RETURN_ERROR;
	
	uint32 add_num = json_object["num"].asUInt();
	uint32 gz_id = json_object["gz_id"].asUInt();
	uint32 exchange_type = json_object["type"].asUInt();
	String strKey = json_object["key"].asString();
	if(add_num == 0 || gz_id == 0 || exchange_type == 0 || strKey == "")
		return SCR_RETURN_ERROR;
	
	uint32 item_modelID1 = 0,item_num1 = 0;
	uint32 item_modelID2 = 0,item_num2 = 0;
	
	if (json_object.isMember("it_md1"))
		item_modelID1 = json_object["it_md1"].asUInt();
	if (json_object.isMember("it_n1"))
		item_num1 = json_object["it_n1"].asUInt();
	if (json_object.isMember("it_md2"))
		item_modelID2 = json_object["it_md2"].asUInt();
	if (json_object.isMember("it_n2"))
		item_num2 = json_object["it_n2"].asUInt();
	
	String it_name1 = "";
	if(item_modelID1)
		it_name1 = sGLMgr.GetItemName(item_modelID1);
	
	String it_name2 = "";
	if(item_modelID2)
		it_name2 = sGLMgr.GetItemName(item_modelID2);
	
	String pack_name = "";
	if(json_object.isMember("pack_name"))
		pack_name = json_object["pack_name"].asString();
	
	Log.Notice("script_process_world_game_command_addexchangecards","add_num[%u] gz_id[%u] exchange_type[%u] strKey[%s]",
					add_num,gz_id,exchange_type,strKey.c_str());
	
	std::map<String, GameExchange> mapExchange;
	uint32 number = 1;
	
	for (uint32 i=0; i<add_num; ++i)
	{
		String new_strQQ = "";
		char str[7] = "";
		while(1)
		{
			for (uint32 j=0; j!=6; ++j)
			{
				str[j] = RandomUInt(0,1) ? RandomUInt(65, 90) : RandomUInt(49, 57);				
			}
			new_strQQ = str + strKey;
			std::map<String, GameExchange>::iterator iter = mapExchange.find(new_strQQ);
			if (iter == mapExchange.end())
				break;
		}
		
		Log.Error("HallManager Test", "number[%u] %s", number++, new_strQQ.c_str());
		GameExchange  *newExchange = sItemMgr.newDumyExchange();
		newExchange->data1 = gz_id;	// 分区号
		
		if(exchange_type == 1)
		{
			newExchange->data3 = 1;		// 礼包类型 1每日 2每周 3新手
			newExchange->data4 = 1; 	// 有效天数 1每日 7每周 9999新手
			newExchange->token = new_strQQ;
			newExchange->name = pack_name;
			
			if(item_modelID1)
			{
				newExchange->item_model1 = item_modelID1;
				newExchange->item_name1 = it_name1;
				newExchange->item_num1 = item_num1;
			}
			
			if(item_modelID2)
			{
				newExchange->item_model2 = item_modelID2;
				newExchange->item_name2 = it_name2;
				newExchange->item_num2 = item_num2;
			}
		}
		else if(exchange_type == 2)
		{
			newExchange->data3 = 2;		// 礼包类型 1每日 2每周 3新手
			newExchange->data4 = 7; 	// 有效天数 1每日 7每周 9999新手
			newExchange->token = new_strQQ;
			newExchange->name = pack_name;
			if(item_modelID1)
			{
				newExchange->item_model1 = item_modelID1;
				newExchange->item_name1 = it_name1;
				newExchange->item_num1 = item_num1;
			}
			
			if(item_modelID2)
			{
				newExchange->item_model2 = item_modelID2;
				newExchange->item_name2 = it_name2;
				newExchange->item_num2 = item_num2;
			}
		}
		else if(exchange_type == 3)
		{
			newExchange->data3 = 3;		// 礼包类型 1每日 2每周 3新手
			newExchange->data4 = 9999; 	// 有效天数 1每日 7每周 9999新手
			newExchange->token = new_strQQ;
			newExchange->name = pack_name;
			
			if(item_modelID1)
			{
				newExchange->item_model1 = item_modelID1;
				newExchange->item_name1 = it_name1;
				newExchange->item_num1 = item_num1;
			}
			
			if(item_modelID2)
			{
				newExchange->item_model2 = item_modelID2;
				newExchange->item_name2 = it_name2;
				newExchange->item_num2 = item_num2;
			}
		}
		else if(exchange_type == 4)
		{// 随时可领取礼包
			
			newExchange->data4 = 9999; 	// 有效天数 1每日 7每周 9999新手
			newExchange->token = new_strQQ;
			newExchange->name = pack_name;
			
			if(item_modelID1)
			{
				newExchange->item_model1 = item_modelID1;
				newExchange->item_name1 = it_name1;
				newExchange->item_num1 = item_num1;
			}
			
			if(item_modelID2)
			{
				newExchange->item_model2 = item_modelID2;
				newExchange->item_name2 = it_name2;
				newExchange->item_num2 = item_num2;
			}
		}
		
		newExchange->group_id = 1;
		newExchange->status = 1;
		newExchange->create_time = sTools.GetCurDateTime();
		newExchange->end_time = sTools.GetCurDateTime(1527782400);
		
		mapExchange.insert(std::make_pair(new_strQQ, *newExchange));
		
		sItemMgr.createExchangeDB(newExchange);
		sItemMgr.freeDumyExchange(newExchange);
	}
	
	return SCR_RETURN_SUCCEED;
}

/* int script_process_world_game_command_reloadmatchbounty(void * info)
{
	if(!info)
		return SCR_RETURN_ERROR;
	
	// GatewayCommand * command = (GatewayCommand *)info;
	// Log.Debug("script_process_world_game_command_reloadmatchbounty","command id[%u],command_type[%u],command_str[%s]",command->cmdid,command->command_type,(command->parameter).c_str());
	
	// sXmlDataMgr.ReloadMatchBounty();
	// sXmlDataMgr.ReloadMatchWeekBounty();
	
	// Log.Notice("script_process_world_game_command_reloadmatchbounty","reload matchbounty item sucessfully!");
	
	return SCR_FORWARD_RETURN_SUCCEED;
} */


int script_process_world_game_command_reloadmessage(void * info)
{
	if(!info)
		return SCR_RETURN_ERROR;
	
	GatewayCommand * command = (GatewayCommand *)info;
	Log.Debug("script_process_world_game_command_reloadmessage","command id[%u],command_type[%u],command_str[%s]",command->cmdid,command->command_type,(command->parameter).c_str());
	

	sMsg.clear();
	
	Log.Notice("script_process_world_game_command_reloadmessage","reload message sucessfully!");
	
	return SCR_FORWARD_RETURN_SUCCEED;
}
//-----------------------------------------------------------------------
int script_process_world_game_command_userbuyitems(void * info)
{
	if(!info)
		return SCR_RETURN_ERROR;
	
	GatewayCommand * command = (GatewayCommand *)info;
	Log.Debug("script_process_world_game_command_userbuyitems","command id[%u],command_type[%u],command_str[%s]",command->cmdid,command->command_type,(command->parameter).c_str());
	
	Json::Value valData;
	if(!sServerMgr.GatewayCommandToJSON(command, &valData))
		return SCR_RETURN_ERROR;
	
	uint32 user_id = command->uid;
	CHECK_USER_SERVER(user_id)
	UserPtr user = sUserMgr.load(user_id);
	if(user.isNull())
		return SCR_RETURN_ERROR;
	
	uint32 game_id = 0;
	uint32 curr_gz_id = 0;
	GameBank bank;
	if (sBankMgr.GetRealBank(user, bank))
	{
		curr_gz_id = bank.gz_id;
		game_id = sGLMgr.GetTargetServerGameid(bank.gz_id, user->getUInt32Field("reg_from"));
	}
	
	uint32 target_gz_id = 0;
	if(game_id == 0 || curr_gz_id == 0 || sXmlDataMgr.IsInGameIds(game_id))
	{// 在本游戏中
		String return_String;
		target_gz_id = sGLMgr.UserBuyItems(valData, return_String);
		Log.Debug("script_process_world_game_command_userbuyitems","target_gz_id[%u]", target_gz_id);
	}
	else
	{// 在其他游戏中
		valData["platform_id"] = user->getUInt32Field("platform_id");
		valData["target_gz_id"] = curr_gz_id;
		valData["agent_id"] = user->getUInt32Field("reg_from");
		
		Json::FastWriter w;
		Log.Debug("script_process_world_game_command_userbuyitems","pid[%u] curr_gz_id[%u] valData[%s]", 
							user->getUInt32Field("platform_id"), curr_gz_id, w.write(valData).c_str());
		target_gz_id = sGLMgr.SendUserBuyItems(valData);
	}
	
	Json::Value valResult;
	Json::FastWriter w;
	
	if(target_gz_id)
	{
		valResult["gz_id"] = target_gz_id;
		valResult["type"] = 12;
		valResult["status"] = target_gz_id ? 1: 0;
		
		command->result = w.write(valResult);
	}
	else
	{// 如果充值失败，在本机上再次进行充值操作
		String return_String;
		target_gz_id = sGLMgr.UserBuyItems(valData, return_String);
		valResult["gz_id"] = target_gz_id;
		valResult["type"] = 12;
		valResult["status"] = target_gz_id ? 1: 0;
		
		command->result = w.write(valResult);
	}
	
	return target_gz_id ? SCR_RETURN_SUCCEED : SCR_RETURN_ERROR;
}

int SERVER_DECL script_process_world_game_command_removeChar(void * info)
{
	if(!info)
		return SCR_RETURN_ERROR;
	
	GatewayCommand * command = (GatewayCommand *)info;
	Log.Debug("script_process_world_game_command_removeChar","command id[%u],command_type[%u],command_str[%s]",command->cmdid,command->command_type,(command->parameter).c_str());
	
	uint32 user_id = command->uid;
	CHECK_USER_SERVER(user_id)
	UserPtr user = sUserMgr.getByHandle(user_id);
	if(user.isNull())
	{
		user = sUserMgr.load(user_id);
		if(user.isNull())
			return SCR_RETURN_ERROR;
	}	

	CharPtr pChr = sCharMgr.getByHandle(user->getUInt32Field("char_id"));
	if(pChr.isNull())
		return SCR_RETURN_ERROR;
	WSSocketPtr pSocket = pChr->getSocket();
	if (!pSocket.isNull())
		pSocket->Disconnect();
	ResourceEvent event;
	event.event_id = ResourceEvent_SaveDB;
	pChr->SendEvent(&event);
	pChr->Delete();
	user->Delete();
	Log.Notice("script_process_world_game_command_removeChar","removeChar user[%u]'s item sucessfully!",user_id);
	
	return SCR_FORWARD_RETURN_SUCCEED;
}

int SERVER_DECL script_process_world_game_command_reloadNotice(void * info)
{
	if(!info)
		return SCR_RETURN_ERROR;
	
	GatewayCommand * command = (GatewayCommand *)info;
	Log.Debug("script_process_world_game_command_reloadNotice","command id[%u],command_type[%u],command_str[%s]",command->cmdid,command->command_type,(command->parameter).c_str());
	
	sNoticeMgr.Clear();
	
	Log.Notice("script_process_world_game_command_reloadNotice","reloadNotice item sucessfully!");
	
	return SCR_FORWARD_RETURN_SUCCEED;
}

/* int SERVER_DECL script_process_world_game_command_reloadroomconf(void * info)
{
	if(!info)
		return SCR_RETURN_ERROR;
	
	// GatewayCommand * command = (GatewayCommand *)info;
	// Log.Debug("script_process_world_game_command_reloadroomconf","command id[%u],command_type[%u],command_str[%s]",command->cmdid,command->command_type,(command->parameter).c_str());
	

	// sXmlDataMgr.ReloadRoomConf();
	
	// Log.Notice("script_process_world_game_command_reloadroomconf","reloadroomcon item sucessfully!");
	
	return SCR_FORWARD_RETURN_SUCCEED;
} */

int SERVER_DECL script_process_world_game_command_reloadsmgameconf(void * info)
{
	if(!info)
		return SCR_RETURN_ERROR;
	
	GatewayCommand * command = (GatewayCommand *)info;
	Log.Debug("script_process_world_game_command_reloadsmgameconf","command id[%u],command_type[%u],command_str[%s]",command->cmdid,command->command_type,(command->parameter).c_str());
	

	sXmlDataMgr.ReloadSMGameConfig();
	
	Log.Notice("script_process_world_game_command_reloadsmgameconf","reloadsmgameconf item sucessfully!");
	
	return SCR_FORWARD_RETURN_SUCCEED;
}

/* int SERVER_DECL script_process_world_game_command_reloadmatchtimes(void * info)
{
	if(!info)
		return SCR_RETURN_ERROR;
	
	// GatewayCommand * command = (GatewayCommand *)info;
	// Log.Debug("script_process_world_game_command_reloadmatchtimes","command id[%u],command_type[%u],command_str[%s]",command->cmdid,command->command_type,(command->parameter).c_str());
	
	// sXmlDataMgr.ReloadMatchTimes();
	// GameServer gs;
	// sChannelMgr.getGameServer(sChannelMgr.getServerID(), gs);
	// if (gs.flag & GameServerFlagMaster)
	// {
		// sServerMgr.SendGatewayCommand(command);
	// }
	
	// Log.Notice("script_process_world_game_command_reloadmatchtimes","reloadmatchtimes item sucessfully!");
	return SCR_FORWARD_RETURN_SUCCEED;
} */

int SERVER_DECL script_process_world_game_command_coalitionuserdata(void * info)
{
	if(!info)
		return SCR_RETURN_ERROR;
	
	// GatewayCommand * command = (GatewayCommand *)info;
	// Log.Debug("script_process_world_game_command_coalitionuserdata","command id[%u],command_type[%u],command_str[%s]",command->cmdid,command->command_type,(command->parameter).c_str());
	
	// uint32 user_id = command->uid;
	// UserPtr user = sUserMgr.getByHandle(user_id);
	// if(user.isNull())
	// {
		// user = sUserMgr.load(user_id);
		// if(user.isNull())
			// return SCR_RETURN_ERROR;
	// }	
	
	// uint32 pid = user->getUInt32Field("platform_id");
	// if(pid != 0)
	// {
		// std::list<GameMarch> marchs;
		// sChannelMgr.getMarchList(&marchs, 0, 10, "type = 10 and status = 1 and sub_type <> %u", sChannelMgr.getGroupID());
		// std::list<GameMarch>::iterator mi, endmi = marchs.end();
		// for(mi = marchs.begin(); mi != endmi; ++mi)
		// {
			// sGLMgr.UniteUserDataFromMatchLog(&(*mi));
		// }
	// }
	
	// Log.Notice("script_process_world_game_command_coalitionuserdata","reloadvipusers user[%u]'s item sucessfully!",user_id);
	
	return SCR_RETURN_SUCCEED;
}

int SERVER_DECL script_process_world_game_command_nospeak(void * info)
{
	if(!info)
		return SCR_RETURN_ERROR;
	
	GatewayCommand * command = (GatewayCommand *)info;
	Log.Debug("script_process_world_game_command_nospeak","command id[%u],command_type[%u],command_str[%s]",command->cmdid,command->command_type,(command->parameter).c_str());
	
	uint32 user_id = command->uid;
	CHECK_USER_SERVER(user_id)
	UserPtr user = sUserMgr.getByHandle(user_id);
	if(user.isNull())
	{
		user = sUserMgr.load(user_id);
		if(user.isNull())
			return SCR_RETURN_ERROR;
	}	

	CharPtr pChr = sCharMgr.load(user->getUInt32Field("char_id"));
	if(pChr.isNull())
	{
		return SCR_RETURN_ERROR;
	}
	
	ADD_CREATURE_FLAG(pChr, en_CreatureFlag_Shutup);
	pChr->SaveDB();
	Log.Notice("script_process_world_game_command_nospeak","reloadvipusers nospeak sucessfully!");
	
	return SCR_FORWARD_RETURN_SUCCEED;
}

int script_process_world_game_command_canspeak(void * info)
{
	if(!info)
		return SCR_RETURN_ERROR;
	
	GatewayCommand * command = (GatewayCommand *)info;
	Log.Debug("script_process_world_game_command_nospeak","command id[%u],command_type[%u],command_str[%s]",command->cmdid,command->command_type,(command->parameter).c_str());
	
	uint32 user_id = command->uid;
	CHECK_USER_SERVER(user_id)
	UserPtr user = sUserMgr.getByHandle(user_id);
	if(user.isNull())
	{
		user = sUserMgr.load(user_id);
		if(user.isNull())
			return SCR_RETURN_ERROR;
	}	

	CharPtr pChr = sCharMgr.getByHandle(user->getUInt32Field("char_id"));
	if(pChr.isNull())
	{
		return SCR_RETURN_ERROR;
	}
	
	CANCEL_CREATURE_FLAG(pChr, en_CreatureFlag_Shutup);
	pChr->SaveDB();
	Log.Notice("script_process_world_game_command_nospeak","reloadvipusers nospeak sucessfully!");
	
	return SCR_RETURN_SUCCEED;
}

int script_process_world_game_command_reloadloging(void * info)
{
	if(!info)
		return SCR_RETURN_ERROR;
	
	GatewayCommand * command = (GatewayCommand *)info;
	Log.Debug("script_process_world_game_command_reloadloging","command id[%u],command_type[%u],command_str[%s]",command->cmdid,command->command_type,(command->parameter).c_str());
	

	sXmlDataMgr.ReloadLoginGift();
	
	Log.Notice("script_process_world_game_command_reloadloging","ReloadLoginGift loadloging sucessfully!");
	
	return SCR_FORWARD_RETURN_SUCCEED;
}

int SERVER_DECL script_process_world_game_command_reloadroulette(void * info)
{
	if(!info)
		return SCR_RETURN_ERROR;
	
	GatewayCommand * command = (GatewayCommand *)info;
	Log.Debug("script_process_world_game_command_reloadroulette","command id[%u],command_type[%u],command_str[%s]",command->cmdid,command->command_type,(command->parameter).c_str());
	
	sXmlDataMgr.LoadChanceConf();
	sXmlDataMgr.LoadBuyLargessXml();
	sXmlDataMgr.LoadHappyFarm();
	Log.Notice("script_process_world_game_command_reloadroulette","LoadChanceConf loadloging sucessfully!");
	
	return SCR_FORWARD_RETURN_SUCCEED;
}

int SERVER_DECL script_process_world_game_command_deleteChannel(void * info)
{
	if(!info)
		return SCR_RETURN_ERROR;
	
	GatewayCommand * command = (GatewayCommand *)info;
	Log.Debug("script_process_world_game_command_deleteChannel","command id[%u],command_type[%u],command_str[%s]",command->cmdid,command->command_type,(command->parameter).c_str());
	
	std::list<ChannelPtr> channels;
	sChannelMgr.getChannelsList(&channels, 0, 1000, "%u - `create_time` > %u AND `status` <> 255", time(0), 2400);
	std::list<ChannelPtr>::iterator ci, endci = channels.end();
	for(ci = channels.begin(); ci != endci; ++ ci)
	{
		(*ci)->Destroy();
	}
	
	Log.Notice("script_process_world_game_command_deleteChannel","deleteChannel channels[%u] sucessfully!", channels.size());

	return SCR_FORWARD_RETURN_SUCCEED;
}

//-----------------------------------------------------------------------
int script_process_world_game_command_reloadgzidconf(void * info)
{
	if(!info)
		return SCR_RETURN_ERROR;
	GatewayCommand * command = (GatewayCommand *)info;
	Log.Debug("script_process_world_game_command_reloadgzidconf","command id[%u],command_type[%u],command_str[%s]",command->cmdid,command->command_type,(command->parameter).c_str());
	sXmlDataMgr.ReloadGZIDName();
	Log.Notice("script_process_world_game_command_reloadgzidconf","reloadlgzId sucessfully!");
	return SCR_FORWARD_RETURN_SUCCEED;
}
//-----------------------------------------------------------------------
int script_process_world_game_command_clearNotices(void * info)
{
	if(!info)
		return SCR_RETURN_ERROR;
	GatewayCommand * command = (GatewayCommand *)info;
	Log.Debug("script_process_world_game_command_clearNotices","command id[%u],command_type[%u],command_str[%s]",command->cmdid,command->command_type,(command->parameter).c_str());
	sNoticeMgr.Clear();
	Log.Notice("script_process_world_game_command_clearNotices","clear notices sucessfully!");
	return SCR_FORWARD_RETURN_SUCCEED;
}
//-----------------------------------------------------------------------
int script_process_world_game_command_reloadVipCards(void * info)
{
	if(!info)
		return SCR_RETURN_ERROR;
	GatewayCommand * command = (GatewayCommand *)info;
	Log.Debug("script_process_world_game_command_reloadVipCards","command id[%u],command_type[%u],command_str[%s]",command->cmdid,command->command_type,(command->parameter).c_str());
	sVipCardMgr.ReloadVipCards();
	Log.Notice("script_process_world_game_command_reloadVipCards","clear notices sucessfully!");
	return SCR_FORWARD_RETURN_SUCCEED;
}

int script_process_world_game_command_noTrade(void * info)
{
	if(!info)
		return SCR_RETURN_ERROR;
	
	GatewayCommand * command = (GatewayCommand *)info;
	Log.Debug("script_process_world_game_command_noTrade","command id[%u],command_type[%u],command_str[%s]",command->cmdid,command->command_type,(command->parameter).c_str());
	
	uint32 user_id = command->uid;
	CHECK_USER_SERVER(user_id)
	ResourcePtr user = sUserMgr.getByHandle(user_id);
	if(user.isNull())
	{
		user = sUserMgr.load(user_id);
		if(user.isNull())
			return SCR_RETURN_ERROR;
	}
	
	CharPtr pChr = sCharMgr.load(user->getUInt32Field("char_id"));
	if(pChr.isNull())
		return SCR_RETURN_ERROR;
	
	ADD_CREATURE_FLAG(pChr, en_CreatureFlag_NoTrade);
		
	pChr->SaveDB();
	
	return SCR_RETURN_SUCCEED;
}

int script_process_world_game_command_canTrade(void * info)
{
	if(!info)
		return SCR_RETURN_ERROR;
	
	GatewayCommand * command = (GatewayCommand *)info;
	Log.Debug("script_process_world_game_command_noTrade","command id[%u],command_type[%u],command_str[%s]",command->cmdid,command->command_type,(command->parameter).c_str());
	
	uint32 user_id = command->uid;
	CHECK_USER_SERVER(user_id)
	ResourcePtr user = sUserMgr.getByHandle(user_id);
	if(user.isNull())
	{
		user = sUserMgr.load(user_id);
		if(user.isNull())
			return SCR_RETURN_ERROR;
	}
	
	CharPtr pChr = sCharMgr.load(user->getUInt32Field("char_id"));
	if(pChr.isNull())
		return SCR_RETURN_ERROR;
	
	CANCEL_CREATURE_FLAG(pChr, en_CreatureFlag_NoTrade);
	pChr->SaveDB();
	
	return SCR_RETURN_SUCCEED;
}

int script_process_world_game_command_enableMCount(void * info)
{
	if(!info)
		return SCR_RETURN_ERROR;
		
	GatewayCommand * command = (GatewayCommand *)info;
	Log.Debug("script_process_world_game_command_enableMCount","command id[%u],command_type[%u],command_str[%s]",command->cmdid,command->command_type,(command->parameter).c_str());
	
	uint32 user_id = command->uid;
	CHECK_USER_SERVER(user_id)
	ResourcePtr user = sUserMgr.getByHandle(user_id);
	if(user.isNull())
	{
		user = sUserMgr.load(user_id);
		if(user.isNull())
			return SCR_RETURN_ERROR;
	}
	
	CharPtr pChr = sCharMgr.load(user->getUInt32Field("char_id"));
	if(pChr.isNull())
		return SCR_RETURN_ERROR;
	
	ADD_CREATURE_FLAG(pChr, en_CreatureFlag_EnMorraCnt);
	pChr->SaveDB();
	
	return SCR_RETURN_SUCCEED;
}

int script_process_world_game_command_disableMCount(void * info)
{
	if(!info)
		return SCR_RETURN_ERROR;
	
	GatewayCommand * command = (GatewayCommand *)info;
	Log.Debug("script_process_world_game_command_disableMCount","command id[%u],command_type[%u],command_str[%s]",command->cmdid,command->command_type,(command->parameter).c_str());
	
	uint32 user_id = command->uid;
	CHECK_USER_SERVER(user_id)
	ResourcePtr user = sUserMgr.getByHandle(user_id);
	if(user.isNull())
	{
		user = sUserMgr.load(user_id);
		if(user.isNull())
			return SCR_RETURN_ERROR;
	}
	
	CharPtr pChr = sCharMgr.load(user->getUInt32Field("char_id"));
	if(pChr.isNull())
		return SCR_RETURN_ERROR;
	
	CANCEL_CREATURE_FLAG(pChr, en_CreatureFlag_EnMorraCnt);
	pChr->SaveDB();
	
	return SCR_RETURN_SUCCEED;
}

int script_process_world_game_command_addMCount(void * info)
{
	if(!info)
		return SCR_RETURN_ERROR;
	
	GatewayCommand * command = (GatewayCommand *)info;
	Log.Debug("script_process_world_game_command_addMCount","command id[%u],command_type[%u],command_str[%s]",command->cmdid,command->command_type,(command->parameter).c_str());
	
	uint32 user_id = command->uid;
	CHECK_USER_SERVER(user_id)
	ResourcePtr user = sUserMgr.getByHandle(user_id);
	if(user.isNull())
	{
		user = sUserMgr.load(user_id);
		if(user.isNull())
			return SCR_RETURN_ERROR;
	}
	
	CharPtr pChr = sCharMgr.load(user->getUInt32Field("char_id"));
	if(pChr.isNull())
		return SCR_RETURN_ERROR;
	
	Json::Reader reader; 
	Json::Value json_object; 
	if (!reader.parse(command->parameter.c_str(), json_object))
		return SCR_RETURN_ERROR;
	if (!json_object.isMember("num"))
		return SCR_RETURN_ERROR;
	uint32 num = json_object["num"].asUInt();
	
	if (pChr->user_data.isPresented(VIPMORRANUM))
		pChr->user_data.Set<uint32>(VIPMORRANUM, *pChr->user_data.Get<uint32>(VIPMORRANUM) + num); 
	else
		pChr->user_data.New<uint32>(VIPMORRANUM, num); 	
	// sVipCardMgr.AddVipValue(pChr, VIPMORRANUM, num);
	
	return SCR_RETURN_SUCCEED;
}

//-----------------------------------------------------------------------
int script_process_world_game_command_addviphonor(void * info)
{
	if(!info)
		return SCR_RETURN_ERROR;
	
	GatewayCommand * command = (GatewayCommand *)info;
	Log.Debug("script_process_world_game_command_addviphonor","command id[%u],command_type[%u],command_str[%s]",command->cmdid,command->command_type,(command->parameter).c_str());
	
	uint32 user_id = command->uid;
	CHECK_USER_SERVER(user_id)
	UserPtr user = sUserMgr.getByHandle(user_id);
	if(user.isNull())
	{
		user = sUserMgr.load(user_id);
		if(user.isNull())
			return SCR_RETURN_ERROR;
	}
	uint32 char_id = user->getUInt32Field("char_id");
	CharPtr chr = sCharMgr.getByHandle(char_id);
	if(chr.isNull())
	{
		chr = sCharMgr.load(char_id);
		if(chr.isNull())
			return SCR_RETURN_ERROR;
	}
	AICreatureBaseInterface *pAiChrInfe = TO_CREATURE_BASE_INTERFACE(chr->getAIInterface());
	if (!pAiChrInfe)
		return SCR_RETURN_ERROR;
	Json::Reader reader; 
	Json::Value json_object; 
	if (!reader.parse(command->parameter.c_str(), json_object))
		return SCR_RETURN_ERROR;
	// vip卡ID
	uint32 vipId = json_object["id"].asUInt();
	uint32 endTime = json_object["mature_time"].asUInt();
	VIPCard vipCard = sVipCardMgr.GetVipCard(vipId);
	if (0 == vipCard.id)
		return SCR_RETURN_ERROR;
	pAiChrInfe->AddVipInfo(vipCard, endTime);
	Log.Notice("script_process_world_game_command_addviphonor","user[%u] add vip honor sucessfully!",user->getHandle());
	return SCR_RETURN_SUCCEED;
}
//-----------------------------------------------------------------------
int script_process_world_game_command_removeviphonor(void * info)
{
	if(!info)
		return SCR_RETURN_ERROR;
	
	GatewayCommand * command = (GatewayCommand *)info;
	Log.Debug("script_process_world_game_command_removeviphonor","command id[%u],command_type[%u],command_str[%s]",command->cmdid,command->command_type,(command->parameter).c_str());
	
	uint32 user_id = command->uid;
	CHECK_USER_SERVER(user_id)
	UserPtr user = sUserMgr.getByHandle(user_id);
	if(user.isNull())
	{
		user = sUserMgr.load(user_id);
		if(user.isNull())
			return SCR_RETURN_ERROR;
	}
	uint32 char_id = user->getUInt32Field("char_id");
	CharPtr chr = sCharMgr.getByHandle(char_id);
	if(chr.isNull())
	{
		chr = sCharMgr.load(char_id);
		if(chr.isNull())
			return SCR_RETURN_ERROR;
	}
	AICreatureBaseInterface *pAiChrInfe = TO_CREATURE_BASE_INTERFACE(chr->getAIInterface());
	if (!pAiChrInfe)
		return SCR_RETURN_ERROR;
	pAiChrInfe->RemoveVipInfo();
	Log.Notice("script_process_world_game_command_removeviphonor","user[%u] remove vip honor sucessfully!",user->getHandle());
	return SCR_RETURN_SUCCEED;
}
//-----------------------------------------------------------------------
int script_process_world_game_command_changeuser(void * info)
{
	if(!info)
		return SCR_RETURN_ERROR;
	
	GatewayCommand * command = (GatewayCommand *)info;
	Log.Debug("script_process_world_game_command_changeuser","command id[%u],command_type[%u],command_str[%s]",command->cmdid,command->command_type,(command->parameter).c_str());
	
	Json::Reader reader; 
	Json::Value json_object; 
	if (!reader.parse(command->parameter.c_str(), json_object))
		return SCR_RETURN_ERROR;
	
	if(!json_object.isMember("sid"))
		return SCR_RETURN_ERROR;
	
	if(!json_object.isMember("tid"))
		return SCR_RETURN_ERROR;
	
	uint32 src_pid = json_object["sid"].asUInt();
	uint32 tag_pid = json_object["tid"].asUInt();
	if(src_pid == tag_pid)
		return SCR_RETURN_ERROR;
	
	std::list<UserPtr> users1;
	sUserMgr.getUserList(&users1, 0, 1, "platform_id = %u", src_pid);
	if(users1.empty())
		return SCR_RETURN_ERROR;	
		
	UserPtr pUser1 = users1.front();
	
	std::list<UserPtr> users2;
	sUserMgr.getUserList(&users2, 0, 1, "platform_id = %u", tag_pid);
	if(users2.empty())
		return SCR_RETURN_ERROR;
		
	UserPtr pUser2 = users2.front();
	if(pUser2.isNull() || pUser1.isNull())
		return SCR_RETURN_ERROR;
	
	CharPtr pChr1 = sCharMgr.load(pUser1->getUInt32Field("char_id"));
	CharPtr pChr2 = sCharMgr.load(pUser2->getUInt32Field("char_id"));
	if(pChr1.isNull() || pChr2.isNull())
		return SCR_RETURN_ERROR;
	
	uint32 game_id = pUser1->getUInt32Field("gz_id");
	uint32 ishere = pChr1->getUInt32Field("ishere");
	if(game_id == 2)
		return SCR_RETURN_ERROR;
	
	if(ishere != 0)
	{
		if(ishere != game_id)
			return SCR_RETURN_ERROR;
	}
	
	if(pChr1->getStatus() != CharacterStatusFree || pChr2->getStatus() != CharacterStatusFree)
		return SCR_RETURN_ERROR;
	
	uint32 bantime = time(0) + 10;
	pUser1->setUInt32Field("ban_time", bantime);
	pUser2->setUInt32Field("ban_time", bantime);
	
	WSSocketPtr pSocket1 = pChr1->getSocket();
	WSSocketPtr pSocket2 = pChr2->getSocket();
	if(!pSocket1.isNull())
		pSocket1->Disconnect();
	if(!pSocket2.isNull())
		pSocket2->Disconnect();

	// 取出新号的资产
	uint32 coins2 = 0, exchange2 = 0, match2 = 0, gold2 = 0;
	sBankMgr.GetItemNum(pChr2, en_ItemModelId_Coins, &coins2);
	sBankMgr.GetItemNum(pChr2, en_ItemModelId_Exchange, &exchange2);
	sBankMgr.GetItemNum(pChr2, en_ItemModelId_Match, &match2);
	sBankMgr.GetItemNum(pChr2, en_ItemModelId_Gold, &gold2);
	
	// 累加到旧号上面
	sBankMgr.addItemNum(game_id, pChr1, en_ItemModelId_Coins, coins2);
	sBankMgr.addItemNum(game_id, pChr1, en_ItemModelId_Exchange, exchange2);
	sBankMgr.addItemNum(game_id, pChr1, en_ItemModelId_Match, match2);
	sBankMgr.addItemNum(game_id, pChr1, en_ItemModelId_Gold, gold2);
	
	// 交换新旧帐号绑定
	pUser2->setUInt32Field("char_id", pChr1->getHandle());
	pChr1->setUInt32Field("userid", pUser2->getHandle());
	
	pUser1->setUInt32Field("char_id", 0);
	pChr2->setUInt32Field("userid", 0);
	
	pUser1->SaveDB();
	pUser2->SaveDB();	
	pChr1->SaveDB();
	pChr2->SaveDB();
	
	pUser1->Delete();
	pUser2->Delete();	
	pChr1->Delete();
	pChr2->Delete();
	
	Log.Notice("script_process_world_game_command_changeuser","srcpid[%u] change to tagpid[%u] sucessfully!", src_pid, tag_pid);
	return SCR_RETURN_SUCCEED;
}
//-----------------------------------------------------------------------
int script_process_world_game_command_getbankdata(void * info)
{
	if(!info)
		return SCR_RETURN_ERROR;
	
	GatewayCommand * command = (GatewayCommand *)info;
	Log.Debug("script_process_world_game_command_getbankdata","command id[%u],command_type[%u],command_str[%s]",command->cmdid,command->command_type,(command->parameter).c_str());
	
	Json::Reader reader; 
	Json::Value json_object; 
	if (!reader.parse(command->parameter.c_str(), json_object))
		return SCR_RETURN_ERROR;
	
	// if(!json_object.isMember("bankid"))
		// return SCR_RETURN_ERROR;
	
	if(!json_object.isMember("pid"))
		return SCR_RETURN_ERROR;
	
	// uint32 bankpid = json_object["bankid"].asUInt();
	uint32 userpid = json_object["pid"].asUInt();
	
	
	std::list<GameBank> lstBankInfo;
	if(!sChannelMgr.getBankList(&lstBankInfo, 0, 1, "`platform_id` = %u and `type` = %u", userpid, 1))
		return SCR_RETURN_ERROR;
	
	if(lstBankInfo.empty())
		return SCR_RETURN_ERROR;
	
	GameBank bank = lstBankInfo.front();
	
	std::list<UserPtr> users1;
	sUserMgr.getUserList(&users1, 0, 1, "platform_id = %u", userpid);
	if(users1.empty())
		return SCR_RETURN_ERROR;	
	UserPtr ptagUser = users1.front();
	if(ptagUser.isNull())
		return SCR_RETURN_ERROR;
	
	CharPtr pChr = sCharMgr.load(ptagUser->getUInt32Field("char_id"));
	if(pChr.isNull())
		return SCR_RETURN_ERROR;
	
	sGLMgr.addItemNum(pChr, en_ItemModelId_Coins, bank.coins);
	sLogDataMgr.UpdateItemsInfoLog(pChr, en_ST_Bank, en_ItemModelId_Coins, en_UNT_Add, bank.coins);
	bank.coins = 0;
	sChannelMgr.updateBankDB(&bank);
	
	Log.Notice("script_process_world_game_command_getbankdata", "script_process_world_game_command_getbankdata userpid[%u] sucessfully!", userpid);
	return SCR_RETURN_SUCCEED;
}
//-----------------------------------------------------------------------
int  script_process_world_game_command_reloadgameinfo(void * info)
{
	if(!info)
		return SCR_RETURN_ERROR;
	GatewayCommand * command = (GatewayCommand *)info;
	Log.Debug("script_process_world_game_command_reloadsevip","command id[%u],command_type[%u],command_str[%s]",command->cmdid,command->command_type,(command->parameter).c_str());
	sXmlDataMgr.ReloadServerIP();
	sBankMgr.ReloadFieldXML();
	Log.Notice("script_process_world_game_command_reloadsevip","clear notices sucessfully!");
	return SCR_FORWARD_RETURN_SUCCEED;
}
//-----------------------------------------------------------------------
int  script_process_world_game_command_additemforbank(void * info)
{
	if(!info)
		return SCR_RETURN_ERROR;
	
	GatewayCommand * command = (GatewayCommand *)info;
	Log.Debug("script_process_world_game_command_additemforbank","command id[%u],command_type[%u],command_str[%s]",command->cmdid,command->command_type,(command->parameter).c_str());
	
	uint32 user_id = command->uid;
	CHECK_USER_SERVER(user_id)
	UserPtr user = sUserMgr.getByHandle(user_id);
	if(user.isNull())
	{
		user = sUserMgr.load(user_id);
		if(user.isNull())
			return SCR_RETURN_ERROR;
	}
	
	Json::Reader reader; 
	Json::Value json_object; 
	if (!reader.parse(command->parameter.c_str(), json_object))
		return SCR_RETURN_ERROR;
	if (!json_object.isMember("script_id"))
		return SCR_RETURN_ERROR;
	uint32 modelId = json_object["script_id"].asUInt();
	if(0 == modelId)
		return SCR_RETURN_ERROR;
	// 数量
	uint32 num = json_object["num"].asUInt();
	// 存款
	sBankMgr.SaveWealthInBank(user, modelId, num, en_Operate_GatewayAdd);
	Log.Notice("script_process_world_game_command_additemforbank","user[%u] additem scriptid[%u] num[%u] sucessfully!",user->getHandle(), modelId,num);
	
	return SCR_RETURN_SUCCEED;
}
//-----------------------------------------------------------------------
int SERVER_DECL script_process_world_game_command_setBothDisableMCount(void * info)
{
	if(!info)
		return SCR_RETURN_ERROR;
	
	GatewayCommand * command = (GatewayCommand *)info;
	Log.Debug("script_process_world_game_command_setBothDisableMCount","command id[%u],command_type[%u],command_str[%s]",command->cmdid,command->command_type,(command->parameter).c_str());
	
	uint32 user_id = command->uid;
	CHECK_USER_SERVER(user_id)
	UserPtr user = sUserMgr.getByHandle(user_id);
	if(user.isNull())
	{
		user = sUserMgr.load(user_id);
		if(user.isNull())
			return SCR_RETURN_ERROR;
	}
	
	CharPtr pChr = sCharMgr.load(user->getUInt32Field("char_id"));
	if(pChr.isNull())
		return SCR_RETURN_ERROR;
	
	Json::Reader reader; 
	Json::Value json_object; 
	if (!reader.parse(command->parameter.c_str(), json_object))
		return SCR_RETURN_ERROR;
	if (!json_object.isMember("op"))
		return SCR_RETURN_ERROR;
	
	uint8 op = json_object["op"].asUInt();
	
	if(!op)
		CANCEL_CREATURE_FLAG(pChr,en_CreatureFlag_BothMCount);
	else if(op == 1)
		ADD_CREATURE_FLAG(pChr, en_CreatureFlag_BothMCount);
	else
		return SCR_RETURN_ERROR;
	
	pChr->SaveDB();
	
	return SCR_RETURN_SUCCEED;
}
//-----------------------------------------------------------------------
int  script_process_world_game_command_reduceitemforbank(void * info)
{
	if(!info)
		return SCR_RETURN_ERROR;
	
	GatewayCommand * command = (GatewayCommand *)info;
	Log.Debug("script_process_world_game_command_reduceitemforbank","command id[%u],command_type[%u],command_str[%s]",command->cmdid,command->command_type,(command->parameter).c_str());
	
	uint32 user_id = command->uid;
	CHECK_USER_SERVER(user_id)
	UserPtr user = sUserMgr.getByHandle(user_id);
	if(user.isNull())
	{
		user = sUserMgr.load(user_id);
		if(user.isNull())
			return SCR_RETURN_ERROR;
	}
	
	Json::Reader reader; 
	Json::Value json_object; 
	if (!reader.parse(command->parameter.c_str(), json_object))
		return SCR_RETURN_ERROR;
	if (!json_object.isMember("script_id"))
		return SCR_RETURN_ERROR;
	uint32 modelId = json_object["script_id"].asUInt();
	if(0 == modelId)
		return SCR_RETURN_ERROR;
	// 数量
	uint32 num = json_object["num"].asUInt();
	// 取款
	sBankMgr.GetWealthFromBank(user, modelId, num, en_Operate_GatewayReduce);
	
	Log.Notice("script_process_world_game_command_reduceitemforbank","user[%u] additem scriptid[%u] num[%u] sucessfully!",user->getHandle(), modelId,num);
	
	return SCR_RETURN_SUCCEED;
}
//-----------------------------------------------------------------------
int script_process_world_game_command_resetbankstatus(void * info)
{
	if(!info)
		return SCR_RETURN_ERROR;
	
	GatewayCommand * command = (GatewayCommand *)info;
	Log.Debug("script_process_world_game_command_resetbankstatus","command id[%u],command_type[%u],command_str[%s]",command->cmdid,command->command_type,(command->parameter).c_str());
	
	uint32 user_id = command->uid;
	CHECK_USER_SERVER(user_id)
	UserPtr user = sUserMgr.getByHandle(user_id);
	if(user.isNull())
	{
		user = sUserMgr.load(user_id);
		if(user.isNull())
			return SCR_RETURN_ERROR;
	}
	
	sBankMgr.ResetGameExchage(user);
	Log.Notice("script_process_world_game_command_resetbankstatus","user[%u]!",user->getHandle());
	return SCR_RETURN_SUCCEED;
}
//-----------------------------------------------------------------------
int script_process_world_game_command_reloadGoldCoronal(void * info)
{
	if(!info)
		return SCR_RETURN_ERROR;
	GatewayCommand * command = (GatewayCommand *)info;
	Log.Debug("script_process_world_game_command_reloadGoldCoronal","command id[%u],command_type[%u],command_str[%s]",command->cmdid,command->command_type,(command->parameter).c_str());
	// sGoldCoronal.ReloadXml();
	Log.Notice("script_process_world_game_command_reloadGoldCoronal","reload gold_coronal.xml sucessfully!");
	return SCR_FORWARD_RETURN_SUCCEED;
}
//-----------------------------------------------------------------------
int script_process_world_game_command_reloadGZIds(void * info)
{
	if(!info)
		return SCR_RETURN_ERROR;
	GatewayCommand * command = (GatewayCommand *)info;
	Log.Debug("script_process_world_game_command_reloadGZIds","command id[%u],command_type[%u],command_str[%s]",command->cmdid,command->command_type,(command->parameter).c_str());
	sXmlDataMgr.ReLoadGameIDXml();
	Log.Notice("script_process_world_game_command_reloadGZIds","reload game_ids.xml sucessfully!");
	return SCR_FORWARD_RETURN_SUCCEED;
}

//-----------------------------------------------------------------------
int SERVER_DECL script_process_world_game_command_reloadipsift(void * info)
{
	if(!info)
		return SCR_RETURN_ERROR;
	GatewayCommand * command = (GatewayCommand *)info;
	Log.Debug("script_process_world_game_command_reloadipsift","command id[%u],command_type[%u],command_str[%s]",command->cmdid,command->command_type,(command->parameter).c_str());
	sShowIP.ReloadXmlFile();
	Log.Notice("script_process_world_game_command_reloadipsift","reload ipsift.xml sucessfully!");
	return SCR_FORWARD_RETURN_SUCCEED;
}
//-----------------------------------------------------------------------
int SERVER_DECL script_process_world_game_command_reloadviproomcoins(void * info)
{
	if(!info)
		return SCR_RETURN_ERROR;
	GatewayCommand * command = (GatewayCommand *)info;
	Log.Debug("script_process_world_game_command_reloadviproomcoins","command id[%u],command_type[%u],command_str[%s]",command->cmdid,command->command_type,(command->parameter).c_str());
	sXmlDataMgr.ReLoadViproomNeedcoins();
	Log.Notice("script_process_world_game_command_reloadviproomcoins","reload ipsift.xml sucessfully!");
	return SCR_FORWARD_RETURN_SUCCEED;
}

// 重载幸运值等级经验配置XMl
int SERVER_DECL script_process_world_game_command_reloadluckyexpsxml(void * info)
{
	if(!info)
		return SCR_RETURN_ERROR;
	GatewayCommand * command = (GatewayCommand *)info;
	Log.Debug("script_process_world_game_command_reloadluckyexpsxml","command id[%u],command_type[%u],command_str[%s]",command->cmdid,command->command_type,(command->parameter).c_str());
	sVipCardMgr.ReLoadLuckyExpsXml();
	Log.Notice("script_process_world_game_command_reloadluckyexpsxml","reload ipsift.xml sucessfully!");
	return SCR_FORWARD_RETURN_SUCCEED;
}
//-----------------------------------------------------------------------
int script_process_world_game_command_reloaddiscountxml(void * info)
{
	if(!info)
		return SCR_RETURN_ERROR;
	// GatewayCommand * command = (GatewayCommand *)info;
	// Log.Debug("script_process_world_game_command_reloaddiscountxml","command id[%u],command_type[%u],command_str[%s]",command->cmdid,command->command_type,(command->parameter).c_str());
	// sDiscountMgr.reloadXml();
	// Log.Notice("script_process_world_game_command_reloaddiscountxml","reload discount.xml sucessfully!");
	return SCR_FORWARD_RETURN_SUCCEED;
}

// 重载赠送乐码配置
int SERVER_DECL script_process_world_game_command_reloadreggivelecardsxml(void * info)
{
	if(!info)
		return SCR_RETURN_ERROR;
	
	GatewayCommand * command = (GatewayCommand *)info;
	Log.Debug("script_process_world_game_command_reloadreggivelecardsxml","command id[%u],command_type[%u],command_str[%s]",command->cmdid,command->command_type,(command->parameter).c_str());
	sXmlDataMgr.ReLoadGiveLeCardsXml();
	Log.Notice("script_process_world_game_command_reloadreggivelecardsxml","reload giveLeCards.xml sucessfully!");
	return SCR_FORWARD_RETURN_SUCCEED;
}

// 重载公共活动配置
int SERVER_DECL script_process_world_game_command_reloadcommonactivityxml(void * info)
{
	if(!info)
		return SCR_RETURN_ERROR;
	
	GatewayCommand * command = (GatewayCommand *)info;
	
	sXmlDataMgr.ReLoadCommonActivity();
	Log.Notice("script_process_world_game_command_reloadcommonactivityxml","reload commonacvitivy.xml sucessfully!");
	return SCR_FORWARD_RETURN_SUCCEED;
}


// 增加乐码
int SERVER_DECL script_process_world_game_command_addlecards(void * info)
{
	if(!info)
		return SCR_RETURN_ERROR;
	
	GatewayCommand * command = (GatewayCommand *)info;
	Log.Debug("script_process_world_game_command_addlecards","command id[%u],command_type[%u],command_str[%s]",command->cmdid,command->command_type,(command->parameter).c_str());
	
	uint32 user_id = command->uid;
	CHECK_USER_SERVER(user_id)
	uint32 pid = 0;
	UserPtr user = sUserMgr.getByHandle(user_id);
	if(user.isNull())
	{
		user = sUserMgr.load(user_id);
	}
	
	if(!user.isNull())
		pid = user->getUInt32Field("platform_id");
	
	Json::Reader reader; 
	Json::Value json_object; 
	if (!reader.parse(command->parameter.c_str(), json_object))
		return SCR_RETURN_ERROR;
	if (!json_object.isMember("num"))
		return SCR_RETURN_ERROR;
	if (!json_object.isMember("type"))
		return SCR_RETURN_ERROR;
	
	uint32 days = 30;
	if(json_object.isMember("days"))
		days = json_object["days"].asUInt();
	
	uint32 num = json_object["num"].asUInt();
	uint32 type = json_object["type"].asUInt();
	if(!num || !type)
		return SCR_RETURN_ERROR;
	
	std::list<GameExchange> cards;
	sGLMgr.CreateLECards(&cards,pid,num,type,days);
	
	Log.Notice("script_process_world_game_command_addlecards","add lecards to pid[%u] type[%u] num[%u] sucessfully!",num);
	return SCR_RETURN_SUCCEED;
}

// 重载水果机记录配置
int SERVER_DECL script_process_world_game_command_reloadfruitxml(void * info)
{
	if(!info)
		return SCR_RETURN_ERROR;
	
	GatewayCommand * command = (GatewayCommand *)info;
	Log.Debug("script_process_world_game_command_reloadfruitxml","command id[%u],command_type[%u],command_str[%s]",command->cmdid,command->command_type,(command->parameter).c_str());
	sXmlDataMgr.ReLoadFruitXml();
	Log.Notice("script_process_world_game_command_reloadfruitxml","reload fruit.xml sucessfully!");
	return SCR_FORWARD_RETURN_SUCCEED;
}

//-----------------------------------------------------------------------
int script_process_world_game_command_reloaditemset(void * info)
{
	if(!info)
		return SCR_RETURN_ERROR;
	GatewayCommand * command = (GatewayCommand *)info;
	Log.Debug("script_process_world_game_command_reloaditemset","command id[%u],command_type[%u],command_str[%s]",command->cmdid,command->command_type,(command->parameter).c_str());
	sXmlDataMgr.LoadItemSetConfig();
	Log.Notice("script_process_world_game_command_reloaditemset","reload awards.xml sucessfully!");
	return SCR_RETURN_SUCCEED;
}

// 重载过滤字符配置
int SERVER_DECL script_process_world_game_command_reloaddenywords(void * info)
{
	if(!info)
		return SCR_RETURN_ERROR;
	GatewayCommand * command = (GatewayCommand *)info;
	Log.Debug("script_process_world_game_command_reloaddenywords","command id[%u],command_type[%u],command_str[%s]",command->cmdid,command->command_type,(command->parameter).c_str());
	sStrConverMgr.LoadDenyWordsTxt();
	Log.Notice("script_process_world_game_command_reloaddenywords","reload deny_words.txt sucessfully!");
	return SCR_RETURN_SUCCEED;
}

// 添加全服邮件  {"title":"标题","contenct":"邮件内容json格式","days":7}
int SERVER_DECL script_process_world_game_command_addservermail(void * info)
{
	if(!info)
		return SCR_RETURN_ERROR;
	
	GatewayCommand * command = (GatewayCommand *)info;
	Log.Debug("script_process_world_game_command_addservermail","command id[%u],command_type[%u]",command->cmdid,command->command_type);
	
	GameMail *pMail = sChannelMgr.newDumyMail();
	if(pMail == NULL)
		return SCR_RETURN_ERROR;
	pMail->group_id = sChannelMgr.getGroupID(); 	// 邮件组ID
	pMail->status = Mail::MailStatusRecv; 			// 邮件状态
	
	pMail->send_serial = command->gz_id; 			//服务器分区ID
	pMail->send_type = en_MailSendType_AllServer;	//全服邮件类型
	
	Json::Reader reader;
	Json::Value json_object,json_contenct;
	if (!reader.parse(command->parameter.c_str(), json_object))
		return SCR_RETURN_ERROR;
	if(!json_object.isMember("title"))
		return SCR_RETURN_ERROR;
	if(!json_object.isMember("content"))
		return SCR_RETURN_ERROR;
	
	pMail->title = DecryptBase64(json_object["title"].asString());
	String strContent = unbase64(json_object["content"].asString());
	
	json_contenct["content"] = strContent;
	
	if(json_object.isMember("items"))	//有附件
	{
		char str[16];
		
		for (Json::Value::iterator iter=json_object["items"].begin(); iter!=json_object["items"].end(); ++iter)
		{
			sprintf(str, "%s", iter.key().asString().c_str());
			json_contenct["items"][str] = StringConverter::parseUnsignedInt((*iter).asString());
		}
		
		pMail->data1 = 1;
	}
	
	// 组合邮件内容
	Json::FastWriter w;
	pMail->contenct = w.write(json_contenct);
	
	uint32 limitDays = 0;
	if(json_object.isMember("days"))
		limitDays = json_object["days"].asUInt();
	
	if(limitDays == 0)
		limitDays = 7;
	
	pMail->data2 = en_ST_AllServerMail;						// 邮件添加原因（日志记录类型）
	pMail->create_time = time(0); 							// 创建时间
	pMail->expiration_time = time(0) + limitDays * 86400; 	// 过期时间
	
	sChannelMgr.addMailDB(pMail);
	sChannelMgr.freeDumyMail(pMail);
	
	Log.Notice("script_process_world_game_command_addservermail","add server mail sucessfully!");
	return SCR_RETURN_SUCCEED;
}

// 操作牧场动物(增加，减少，清除）可以单独清楚一个动物或者清楚所有动物
//-----------------------------------------------------------------------
int SERVER_DECL script_process_world_game_command_operatorfarm(void * info)
{
	if(!info)
		return SCR_RETURN_ERROR;
	
	/* GatewayCommand * command = (GatewayCommand *)info;
	Log.Debug("script_process_world_game_command_operatorfarm","command id[%u],uid[%u],command_type[%u]",
						command->cmdid,command->uid,command->command_type);
	
	uint32 user_id = command->uid;
	CHECK_USER_SERVER(user_id)
	UserPtr pUser = sUserMgr.getByHandle(user_id);
	if(pUser.isNull())
	{// 检查用户是否存在
		pUser = sUserMgr.load(user_id);
		if(pUser.isNull())
			return SCR_RETURN_ERROR;
	}
	
	Json::Reader reader;
	Json::Value json_object;
	if (!reader.parse(command->parameter.c_str(), json_object))
		return SCR_RETURN_ERROR;
	
	// 操作模式
	if(!json_object.isMember("op_mode"))
		return SCR_RETURN_ERROR;
	
	// 动物模式ID
	if(!json_object.isMember("model_id"))
		return SCR_RETURN_ERROR;
	
	// 操作数量
	if(!json_object.isMember("num"))
		return SCR_RETURN_ERROR;
	
	uint8 op_mode = json_object["op_mode"].asUInt();
	uint8 model_id = json_object["model_id"].asUInt();
	uint8 num = json_object["num"].asUInt();
	
	bool re = sBankMgr.OperatorFarmByCommand(pUser,op_mode,model_id,num);
	if(!re)
		return SCR_RETURN_ERROR; */
	
	return SCR_RETURN_SUCCEED;
}

//-----------------------------------------------------------------------
int SERVER_DECL script_process_world_game_command_debugSocketList(void * info)
{
	std::list<ResourcePtr> lstSockets;	
	sWSSocketMgr.getSocketList(lstSockets);
	std::list<ResourcePtr>::iterator iter,enditer = lstSockets.end();
	for (iter = lstSockets.begin(); iter != enditer; ++iter)
	{
		WSSocketPtr socket = *iter;
		if (!socket.isNull() && socket->isWebSocket())
		{
			UserPtr pUser = socket->m_User.getResourcePtr();
			if (!pUser.isNull())
			{
				Log.Debug("Socket","Info Socket[%u] FD[%d]  IP[%s:%d] User[%u] Character[%u] isCT[%u] last_time[%u], User reg_time[%s] status[%u] last_time[%s]", 
					socket->getHandle(),socket->GetFd(),socket->GetIP(),
					socket->GetPort(),socket->m_User._handle,socket->m_Char._handle, 
					socket->isCheckTimeOut(), ((now()-socket->getLastTimer())/1000),
					sTools.GetCurDateTime(pUser->getUInt32Field("reg_time")).c_str(), 
					pUser->getUInt32Field("status"), sTools.GetCurDateTime(pUser->getUInt32Field("ll_time")).c_str()); 
			}
		}
	}
	
	return SCR_RETURN_SUCCEED;
}

// #include <gperftools/heap-checker.h>

// Test some function
int SERVER_DECL script_process_world_game_command_testsomefunc(void * info)
{
	// HeapLeakChecker::NoGlobalLeaks();
	
	Log.Debug("script_process_world_game_command_testsomefunc","test some function sucess!");
	return SCR_RETURN_SUCCEED;
}

// 派乐盟兑换道具
int SERVER_DECL script_process_world_game_command_pailemengexchange(void * info)
{
	if(!info)
		return SCR_RETURN_ERROR;
	
	GatewayCommand * command = (GatewayCommand *)info;
	Log.Debug("script_process_world_game_command_pailemengexchange","command id[%u],command_type[%u],command_str[%s]",command->cmdid, command->command_type, (command->parameter).c_str());
	
	uint32 user_id = command->uid;
	CHECK_USER_SERVER(user_id)
	
	UserPtr pUser = sUserMgr.load(user_id);
	if(pUser.isNull())
		return SCR_RETURN_ERROR;
	
	uint32 char_id = pUser->getUInt32Field("char_id");
	CharPtr pChr = sCharMgr.load(char_id);
	if(pChr.isNull())
		return SCR_RETURN_ERROR;
	
	Json::Reader reader; 
	Json::Value json_object; 
	if (!reader.parse(command->parameter.c_str(), json_object))
		return SCR_RETURN_ERROR;
	
	if (!json_object.isMember("goods_id"))		// 商品ID
		return SCR_RETURN_ERROR;
	if (!json_object.isMember("goods_num"))		// 兑换商品数量
		return SCR_RETURN_ERROR;
	if (!json_object.isMember("cast_model"))	// 消耗道具模式ID
		return SCR_RETURN_ERROR;
	if (!json_object.isMember("cast_num"))		// 消耗道具数量
		return SCR_RETURN_ERROR;
	
	uint32 goods_id = json_object["goods_id"].asUInt();
	uint32 goods_num = json_object["goods_num"].asUInt();
	uint32 cast_model = json_object["cast_model"].asUInt();
	uint32 cast_num = json_object["cast_num"].asUInt();
	
	String msg = "sucess";
	bool bSucess = true;
	do
	{
		if(cast_model == 0 || cast_num == 0)
		{// 错误的参数数值
			bSucess = false;
			msg = "error cast";
			break;
		}
		
		uint32 curr_num = sGLMgr.GetItemNum(pChr, cast_model);
		if(curr_num < cast_num)
		{// 兑换货币不足
			bSucess = false;
			msg = "coins need";
			break;
		}
		
		if(!sGLMgr.reduceItemNum(pChr, cast_model, cast_num))
		{// 兑换货币不足
			bSucess = false;
			msg = "coins need";
			break;
		}
		
		// 记录兑换日志
		sLogDataMgr.UpdateItemsInfoLog(pChr, en_ST_ExChangeGoods, cast_model, en_UNT_Reduce, cast_num, goods_id, goods_num);
		
	}while(0);
	
	Json::Value valResult;
	valResult["type"] = command->command_type;
	valResult["status"] = bSucess ? 1 : 0;
	valResult["msg"] = msg;
	
	Json::FastWriter w;
	command->result = w.write(valResult);
	
	WorldPacket packet;
	if(sProtocolsMgr.CreateBuyGoodsPacket(&packet, goods_id, bSucess, ""))
		sGLMgr.SendProtocolsToChr(pChr, &packet);
	
	return SCR_RETURN_SUCCEED;
}

// 封停俱乐部
int SERVER_DECL script_process_world_game_command_stopclub(void * info)
{
	if(!info)
		return SCR_RETURN_ERROR;
	
	GatewayCommand * command = (GatewayCommand *)info;
	Log.Debug("script_process_world_game_command_pailemengexchange","command id[%u],command_type[%u],command_str[%s]",command->cmdid, command->command_type, (command->parameter).c_str());
	
	Json::Reader reader; 
	Json::Value json_object; 
	if (!reader.parse(command->parameter.c_str(), json_object))
		return SCR_RETURN_ERROR;
	
	if (!json_object.isMember("club_id"))		// 俱乐部ID
		return SCR_RETURN_ERROR;
	
	uint32 club_id = json_object["club_id"].asUInt();
	bool bSucess = sCenterClubMgr.ManagerStopClub(club_id);
	
	Json::Value valResult;
	valResult["type"] = command->command_type;
	valResult["status"] = bSucess ? 1 : 0;
	
	Json::FastWriter w;
	command->result = w.write(valResult);
	return SCR_RETURN_SUCCEED;
}

// 操作比赛赛区信息
int SERVER_DECL script_process_world_game_command_opmatchzone(void * info)
{
	if(!info)
		return SCR_RETURN_ERROR;
	
	GatewayCommand * command = (GatewayCommand *)info;
	Log.Debug("script_process_world_game_command_opmatchzone","command id[%u],command_type[%u],command_str[%s]",command->cmdid, command->command_type, (command->parameter).c_str());
	
	Json::Reader reader;
	Json::Value json_object; 
	if (!reader.parse(command->parameter.c_str(), json_object))
		return SCR_RETURN_ERROR;
	
	if (!json_object.isMember("op"))		// 操作(1 添加 2 修改）
		return SCR_RETURN_ERROR;
	
	uint32 op = json_object["op"].asUInt();
	bool bSucess = false;

#ifdef CENTERMATCH
	if(op == 1)			// 添加赛区信息
		bSucess = sCenterMatchZoneMgr.GatewayAddCenrerMatchZone(command->parameter) == 0;
	else if(op == 2)	// 修改赛区信息
		bSucess = sCenterMatchZoneMgr.GatewayChangeCenrerMatchZone(command->parameter) == 0;
	else
		return SCR_RETURN_ERROR;
#endif
	
	Json::Value valResult;
	valResult["type"] = command->command_type;
	valResult["status"] = bSucess ? 1 : 0;
	
	Json::FastWriter w;
	command->result = w.write(valResult);
	return SCR_RETURN_SUCCEED;
}

// 重新记载组局开具费用配置
int SERVER_DECL script_process_world_game_command_reloadcenterbattleopencoinsxml(void * info)
{
	Log.Debug("script_process_world_game_command_reloadcenterbattleopencoinsxml","reload center battle opencoins xml!");
	
	sXmlDataMgr.ReLoadCenterBattleOpenCoinsXml();
	return SCR_RETURN_SUCCEED;
}

// 重载centerbattle_modeai.xml
int SERVER_DECL script_process_world_game_command_reloadcenterbattlemodeai(void * info)
{
	Log.Debug("script_process_world_game_command_reloadcenterbattlemodeai","reload center battle modeai xml!");
	
	sXmlDataMgr.ReLoadCenterBattleModeXml();
	return SCR_RETURN_SUCCEED;
}

// 重载buy_union_goods.xml
int SERVER_DECL script_process_world_game_command_reloadbuyuniongoodsxml(void * info)
{
	Log.Debug("script_process_world_game_command_reloadbuyuniongoodsxml","reload buy_union_goods.xml!");
	
	sXmlDataMgr.ReloadBuyUnionGoodsXml();
	return SCR_RETURN_SUCCEED;
}

// 去掉玩家周卡月卡
int SERVER_DECL script_process_world_game_command_opmonthcardtimer(void * info)
{
	if(!info)
		return SCR_RETURN_ERROR;
	
	Log.Debug("script_process_world_game_command_opmonthcardtimer","op monthcard timer");
	
	GatewayCommand * command = (GatewayCommand *)info;
	
	uint32 user_id = command->uid;
	UserPtr pUser = sUserMgr.getByHandle(user_id);
	if(pUser.isNull())
	{
		pUser = sUserMgr.load(user_id);
		if(pUser.isNull())
			return SCR_RETURN_ERROR;
	}
	
	uint32 char_id = pUser->getUInt32Field("char_id");
	CharPtr pChr = sCharMgr.getByHandle(char_id);
	if(pChr.isNull())
	{
		pChr = sCharMgr.load(char_id);
		if(pChr.isNull())
			return SCR_RETURN_ERROR;
	}
	Json::Reader reader; 
	Json::Value json_object; 
	if (!reader.parse(command->parameter.c_str(), json_object))
		return SCR_RETURN_ERROR;
	
	if (!json_object.isMember("card_type"))	// 卡类型（1 周卡 2 月卡）
		return SCR_RETURN_ERROR;
	if (!json_object.isMember("op_type"))	// 操作类型（1 增加 2 减少）
		return SCR_RETURN_ERROR;
	if (!json_object.isMember("days"))		// 天数（不足扣除直接扣成0）
		return SCR_RETURN_ERROR;
	
	uint32 opType = json_object["op_type"].asUInt();
	uint32 days = json_object["days"].asUInt() * 86400 + 86400;
	uint32 cardType = json_object["card_type"].asUInt();
	
	String vip_key = "VIP_WEEKCARD";
	if(cardType == 2)
		vip_key = "VIP_MONTHCARD";
	
	AICreatureBaseInterface * pAiChrInfe = TO_CREATURE_BASE_INTERFACE(pChr->getAIInterface());
	if(!pAiChrInfe)
		return SCR_RETURN_ERROR;
	
	if(opType == 2)
		pAiChrInfe->ReduceXMLValue(vip_key, days);
	else
		pAiChrInfe->AddXMLValue(vip_key, days);
	
	sGLMgr.NoticeWelfare(pChr);
	Log.Debug("script_process_world_game_command_opmonthcardtimer","op monthcard timer days[%u] sucess!", days);
	return SCR_RETURN_SUCCEED;
}

// 重载my_gameids.xml
int SERVER_DECL script_process_world_game_command_reloadmygameidsxml(void * info)
{
	Log.Debug("script_process_world_game_command_reloadmygameidsxml","reload my_gameids xml!");
	
	sXmlDataMgr.ReLoadGameIdsXml();
	return SCR_RETURN_SUCCEED;
}

// 重载不同平台赠送道具配置register_give_items.xml
int SERVER_DECL script_process_world_game_command_reloadregistergiveitemsxml(void * info)
{
	Log.Debug("script_process_world_game_command_reloadregistergiveitemsxml","reload register_give_items xml!");
	
	sXmlDataMgr.ReLoadRegisterGiveItemsXml();
	return SCR_RETURN_SUCCEED;
}

// 重载不同平台赠送道具配置item_model_name.xml
int SERVER_DECL script_process_world_game_command_reloadItemModelNameXml(void * info)
{
	Log.Debug("script_process_world_game_command_reloadItemModelNameXml","reload item_model_name xml!");
	
	sXmlDataMgr.ReLoadItemModelNameXml();
	return SCR_RETURN_SUCCEED;
}

// 重载公共排行配置
int SERVER_DECL script_process_world_game_command_reloadCommonOrderXml(void * info)
{
	Log.Debug("script_process_world_game_command_reloadCommonOrderXml","reload common_order xml!");
	
	sXmlDataMgr.ReLoadCommonOrderXml();
	return SCR_RETURN_SUCCEED;
}

// 重载游戏名称配置
int SERVER_DECL script_process_world_game_command_reloadGameNameXml(void * info)
{
	Log.Debug("script_process_world_game_command_reloadGameNameXml","reload game_name xml!");
	
	sXmlDataMgr.ReLoadGameNameXml();
	return SCR_RETURN_SUCCEED;
}

// 重载公共签到配置
int SERVER_DECL script_process_world_game_command_reloadCommonSignXml(void * info)
{
	Log.Debug("script_process_world_game_command_reloadCommonSignXml","reload common_sign xml!");
	sXmlDataMgr.ReLoadCommonSignInfoXml();
	return SCR_RETURN_SUCCEED;
}

// 重载加载公共成就配置
int SERVER_DECL script_process_world_game_command_reloadBuildCommonEffortsXml(void * info)
{
	Log.Debug("script_process_world_game_command_reloadBuildCommonEffortsXml","reload build_common_effort xml!");
	sXmlDataMgr.ReLoadBuildEffortsXml();
	return SCR_RETURN_SUCCEED;
}

// 重载gateway_httphost.xml 配置
int SERVER_DECL script_process_world_game_command_reloadGateWayHttpHostXml(void * info)
{
	Log.Debug("script_process_world_game_command_reloadGateWayHttpHostXml","reload gateway_httphost xml!");
	sXmlDataMgr.ReLoadGatewayHttpHoseAddr();
	return SCR_RETURN_SUCCEED;
}

// 服务器作弊网关
int SERVER_DECL script_process_world_game_command_testprotocols(void * info)
{
	GatewayCommand * command = (GatewayCommand *)info;
	
	uint32 user_id = command->uid;
	UserPtr pUser = sUserMgr.load(user_id);
	if(pUser.isNull())
		return SCR_RETURN_ERROR;
	
	uint32 char_id = pUser->getUInt32Field("char_id");
	CharPtr pChr = sCharMgr.load(char_id);
	if(pChr.isNull())
		return SCR_RETURN_ERROR;
	
	AICreatureBaseInterface * pAiChrInfe = TO_CREATURE_BASE_INTERFACE(pChr->getAIInterface());
	if(!pAiChrInfe)
		return SCR_RETURN_ERROR;
	
	Json::Reader reader; 
	Json::Value json_object; 
	if (!reader.parse(command->parameter.c_str(), json_object))
		return SCR_RETURN_ERROR;
	
	if (!json_object.isMember("op_type"))	// 操作类型
		return SCR_RETURN_ERROR;
	if (!json_object.isMember("data1"))		// 操作数据1
		return SCR_RETURN_ERROR;	
	
	uint32 opType = json_object["op_type"].asUInt();
	uint32 data1 = json_object["data1"].asUInt();
	
	uint32 data2 = 0;
	if (json_object.isMember("data2") && json_object["data2"].isUInt())
		data2 = json_object["data2"].asUInt();
	
	Log.Debug("script_process_world_game_command_testprotocols","opType[%u] data1[%u] data2[%u]", opType, data1, data2);
	switch(opType)
	{
	case 1:	// 加道具
		{
			sGLMgr.addItemNum(pChr, data1, data2);
			break;
		}
	case 2:	// 减道具
		{
			sGLMgr.reduceItemNum(pChr, data1, data2);
			break;
		}
	case 3:	// 充值
		{
			uint32 curTime = time(0);
			uint32 op = 1;
			bool isDiscount = false; 	// 是否加送铜钱
			uint32 modelId = data1;		// 模式ID
			uint32 num = data2;			// 数量
			WorldPacket packet;			// 协议包
			
			if(modelId >= sXmlDataMgr.GetConfXMLValue("UNION_GOODS_START_PACKETID") 
				&& modelId <= sXmlDataMgr.GetConfXMLValue("UNION_GOODS_END_PACKETID"))
			{// 打包物品（起始和结束模式ID）
				std::map<uint32, uint32> mapGoods;
				if(!sGLMgr.UserBuyUnionGoods(pChr, modelId, num, &mapGoods))
					return SCR_RETURN_ERROR;
			}
			else
			{
				Log.Debug("script_process_world_game_command_testprotocols","modelId[%u] num[%u] 222", modelId, num);
				if (modelId < ItemModel_Coins && modelId > 500)
				{// 购买各种VIP卡或礼包
					// vip卡ID
					VIPCard vipCard = sVipCardMgr.GetVipCard(modelId);
					if (0 == vipCard.id)
						return SCR_RETURN_ERROR;
					// 是否可购买更多			
					if ((vipCard.flag & en_VipFlag_NoMore) && 
						sVipCardMgr.HaveVIPCard(pChr, modelId))
						return SCR_RETURN_ERROR;
					if (vipCard.type == en_VipType_Body)
					{// 形象
						uint32 bodyid = vipCard.money;
						pAiChrInfe->AddCreatureBody(bodyid, curTime + (vipCard.days*60*60*24));
						pChr->setUInt32Field("id", bodyid);
						if (sProtocolsMgr.CreateBodyListPacket(&packet, pChr))
							sGLMgr.SendProtocolsToChr(pChr, &packet);
						vipCard.money = 0;
						vipCard.coins *= num;
					}
					else
					{
						isDiscount = (vipCard.flag & en_VipFlag_Discount);
						vipCard.coins *= num;
						vipCard.money *=num;
						vipCard.days *= num;
						vipCard.morraNum *= num;
						vipCard.bugle *= num;
						vipCard.signin *= num;					
						pAiChrInfe->AddNewVIPInfo(vipCard);
						if (vipCard.type == en_VipType_Welfare)
						{
							sGLMgr.NoticeWelfare(pChr);
							Log.Debug("script_process_world_game_command_testprotocols","modelId[%u] num[%u] 444", modelId, num);
						}
					}
					
					pAiChrInfe->SetXMLData("USERBUYVIP_TIME",curTime);
					pChr->SaveDB();
					
					if (vipCard.type == en_VipType_FirstBuy)
					{// 作首充标记
						Log.Debug("script_process_world_game_command_testprotocols","vip_id[%u] vip_day[%u]", vipCard.vip_id, vipCard.vip_day);
						sBankMgr.AddPublicData(pUser, en_PublicData_FirstBuy, num, en_ST_Gateway_Buy);
						sBankMgr.SetPublicData(pUser, en_PublicData_FirstBuyTimer, curTime);
						
						if(vipCard.vip_id)
						{
							// 赠送VIP天数
							VIPCard vipCardFree = sVipCardMgr.GetVipCard(vipCard.vip_id);
							if(vipCardFree.id != 0)
							{
								uint32 endTime = time(0) + vipCard.vip_day * 86400;							
								pAiChrInfe->AddVipInfo(vipCardFree, endTime);
							}
						}
						
						// 发送关闭首充通道
						if (sProtocolsMgr.CreateTellToDoPacket(&packet, en_RemindType_CloseFirstBuy))
							sGLMgr.SendProtocolsToChr(pChr, &packet);
					}
					
					if(vipCard.coins)
					{
						num = vipCard.coins;
						modelId = ItemModel_Coins;					
					}
					else
					{
						modelId = ItemModel_Golds;
						num = vipCard.money;
					}
					
					// 添加喇叭
					if (vipCard.bugle)
					{
						sGLMgr.addItemNum(pChr, ItemModel_Bugle, vipCard.bugle);
						sLogDataMgr.UpdateItemsByUserBuyLog(pChr, ItemModel_Bugle, vipCard.bugle);
					}
					
					// 添加签到卡
					if (vipCard.signin)
					{
						sGLMgr.addItemNum(pChr, ItemModel_BuQianKa, vipCard.signin);
						sLogDataMgr.UpdateItemsByUserBuyLog(pChr, ItemModel_BuQianKa, vipCard.signin);
					}
					
					// 添加钻石/房卡
					if(vipCard.diamand)
					{
						sGLMgr.addItemNum(pChr, ItemModel_DiamondOpen, vipCard.diamand);
						sLogDataMgr.UpdateItemsByUserBuyLog(pChr, ItemModel_DiamondOpen, vipCard.diamand);
					}
					
				}
				
				ItemModelPtr pIModel = sItemModelMgr.load(modelId);
				if(pIModel.isNull())
					return SCR_RETURN_SUCCEED;			
				
				if(op == 1)// 加钱
				{
					if(modelId == ItemModel_Coins)
					{// 购买的铜钱
						uint32 n_time = time(0);
						uint32 begin_time = sXmlDataMgr.GetConfXMLValue("BUY_ACTIVITY_BEGIN");
						uint32 end_time = sXmlDataMgr.GetConfXMLValue("BUY_ACTIVITY_END");
						if(isDiscount && begin_time && end_time && n_time >= begin_time && n_time <= end_time)
						{
							num = (uint32)(num * ((float)sXmlDataMgr.GetConfXMLValue("BUY_PREFER_PERCENT") * 0.01f));						
						}
						
						sGLMgr.addItemNum(pChr, modelId, num);	
					}
					
					else if (pIModel->getUInt32Field("type") == 1 && pIModel->getUInt32Field("sub_type") == 1)
					{
						sGLMgr.AddMammonCard(pChr, modelId, num);
					}
					else
					{
						if (pIModel->getUInt32Field("type") != 2)
						{
							uint32 base = pIModel->getUInt32Field("value");
							num *= (base?base:1);
						}
						sGLMgr.addItemNum(pChr, modelId, num);
					}
					// 记录日志
					sLogDataMgr.UpdateItemsByUserBuyLog(pChr, modelId, num);
				}
			}
			break;
		}
	case 4:	// 修改平台ID
		{
			pUser->setUInt32Field("reg_from", data1);
			pUser->SaveDB();
		}
		break;
	default:
		return SCR_RETURN_ERROR;
	}
	
	
	return SCR_RETURN_SUCCEED;
}

//-----------------------------------------------------------------------
int 	server_hook_loop(uint32 serverid)
{
static uint32 	hook_checktimer = now();	
	if(now() - hook_checktimer >= sXmlDataMgr.GetConfXMLValue("USER_CHECK_INTERVAL"))
	{// 清除离线玩家
		// GameServer gs;
		uint32 serverid = sChannelMgr.getServerID();
		std::set<ResourceProxy> setChars;   
		// 找出所有需要删除的角色
		std::list<ResourcePtr> chars;
		sCharMgr.getResourceList(&chars);
		std::list<ResourcePtr>::iterator iter, enditer = chars.end();
		for (iter = chars.begin(); iter != enditer; ++ iter)
		{
			CharPtr pChr = *iter; 
			if(pChr.isNull() || !pChr->isLoaded() || pChr->isNPC())
				continue;
			AICreatureBaseInterface * pACCI = TO_CREATURE_BASE_INTERFACE(pChr->getAIInterface());
			if(pACCI)
			{
				ChannelPtr channel = pACCI->GetChannelPtr();
				if(!channel.isNull())
					continue;
				if(pACCI->IsRemoveSelf())
				{
					ResourceProxy pro = (*iter);
					if (pro.isNull())
						continue;
					setChars.insert(pro);
				}
			}
		}
		
		uint32 time_now = time(0);
		
		// 执行删除操作
		std::set<ResourceProxy>::iterator siter, endsiter = setChars.end();
		for(siter = setChars.begin(); siter != endsiter; ++ siter)
		{
			CharPtr pChr = sCharMgr.getByHandle((*siter)._handle); 
			if(pChr.isNull() || !pChr->isLoaded() || pChr->isNPC())
				continue;
			WSSocketPtr pSocket = pChr->getSocket();
			if (!pSocket.isNull())
				continue;
			
			AICreatureBaseInterface * pACCI = TO_CREATURE_BASE_INTERFACE(pChr->getAIInterface());
			if(pACCI)
			{
				ChannelPtr channel = pACCI->GetChannelPtr();
				if(!channel.isNull())
					continue;
				
				if(pACCI->IsRemoveSelf())
				{
					Log.Notice("ServerHook Test", "delete chr[%u] status[%u]", pChr->getHandle(), pChr->getStatus());
					UserPtr pUser = sUserMgr.getByHandle(pChr->getUInt32Field("userid"));	
					if (!pUser.isNull() && pUser->isLoaded())
					{
						// 玩家才注册的不马上删除他
						if(pUser->getUInt32Field("reg_time") + 60 >= time_now)
							continue;
						
						//玩家登陆至少60秒才删除
						if(pUser->getUInt32Field("ll_time") > 0 && pUser->getUInt32Field("ll_time") + 60 >= time_now)
							continue;
						
						if (serverid == 0 || pUser->getUInt32Field("active_gz_id") == serverid)
						{
							sBankMgr.DisconnectServer(pUser, pUser->getUInt32Field("gz_id"));	
							pUser->setUInt32Field("active_gz_id", 0);
						}
						
						// 离线前设置玩家好友状态为离线状态
						sCenterFriendsMgr.UpdateFriendGameStatus(pChr, enFriendGameStatus_Free, false);
						sCenterClubMemberMgr.UpdateMemberOffline(pUser->getUInt32Field("platform_id"));
						
						pUser->setUInt32Field("status", UserStatus_Releasing);
						pUser->SaveDB();
						pChr->Delete(); 
						pUser->setUInt32Field("status", UserStatus_Offline);
						pUser->SaveDB();
						pUser->Delete();
						//AccountDatabase.WaitExecute("update `users` set `status`= `status` &~ %u where `uid` = %u", 
						//					UserStatus_Releasing, user_id);
					}
					else
					{
						pChr->Delete();
					}
				}
			}
		}
		chars.clear();			
		hook_checktimer = now();
	}
	return true;
}

int 	server_hook_start(uint32 serverid)
{
	// 清除在线状态
	Log.Debug("server_hook_start","clear users status begin!");
	uint16 server_id = sChannelMgr.getServerID();
	GameServer gs;
	sChannelMgr.getGameServer(server_id, gs);
	if (gs.flag & GameServerFlagSlave)
	{// 从服务器
		AccountDatabase.WaitExecute("update `users` set `status` = %u,`active_gz_id`=0 where `status` > 0 AND `active_gz_id`=%u", UserStatus_Offline, server_id);
	}
	else
	{
		AccountDatabase.WaitExecute("update `users` set `status` = %u,`active_gz_id`=0 where `status` > 0 AND (`active_gz_id`=0 OR `active_gz_id`=%u)", UserStatus_Offline, server_id);
	}
	sGoodsMgr.load();	
	Log.Debug("server_hook_start","clear users status end!");		
	return true;
}



